context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace NAudio.Wave { /// <summary> /// Represents an MP3 Frame /// </summary> public class Mp3Frame { private static readonly int[,,] bitRates = new int[,,] { { // MPEG Version 1 { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 }, // Layer 1 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 }, // Layer 2 { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 }, // Layer 3 }, { // MPEG Version 2 & 2.5 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 }, // Layer 1 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer 2 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 }, // Layer 3 (same as layer 2) } }; private static readonly int[,] samplesPerFrame = new int[,] { { // MPEG Version 1 384, // Layer1 1152, // Layer2 1152 // Layer3 }, { // MPEG Version 2 & 2.5 384, // Layer1 1152, // Layer2 576 // Layer3 } }; private static readonly int[] sampleRatesVersion1 = new int[] {44100, 48000, 32000}; private static readonly int[] sampleRatesVersion2 = new int[] {22050, 24000, 16000}; private static readonly int[] sampleRatesVersion25 = new int[] {11025, 12000, 8000}; //private short crc; private const int MaxFrameLength = 16*1024; /// <summary> /// Reads an MP3 frame from a stream /// </summary> /// <param name="input">input stream</param> /// <returns>A valid MP3 frame, or null if none found</returns> public static Mp3Frame LoadFromStream(Stream input) { return LoadFromStream(input, true); } /// <summary>Reads an MP3Frame from a stream</summary> /// <remarks>http://mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm has some good info /// also see http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx /// </remarks> /// <returns>A valid MP3 frame, or null if none found</returns> public static Mp3Frame LoadFromStream(Stream input, bool readData) { byte[] headerBytes = new byte[4]; int bytesRead = input.Read(headerBytes, 0, headerBytes.Length); if (bytesRead < headerBytes.Length) { // reached end of stream, no more MP3 frames return null; } Mp3Frame frame = new Mp3Frame(); while (!IsValidHeader(headerBytes, frame)) { // shift down by one and try again headerBytes[0] = headerBytes[1]; headerBytes[1] = headerBytes[2]; headerBytes[2] = headerBytes[3]; bytesRead = input.Read(headerBytes, 3, 1); if (bytesRead < 1) { return null; } } /* no longer read the CRC since we include this in framelengthbytes if (this.crcPresent) this.crc = reader.ReadInt16();*/ int bytesRequired = frame.FrameLength - 4; if (readData) { frame.RawData = new byte[frame.FrameLength]; Array.Copy(headerBytes, frame.RawData, 4); bytesRead = input.Read(frame.RawData, 4, bytesRequired); if (bytesRead < bytesRequired) { // TODO: could have an option to suppress this, although it does indicate a corrupt file // for now, caller should handle this exception throw new EndOfStreamException("Unexpected end of stream before frame complete"); } } else { // n.b. readData should not be false if input stream does not support seeking input.Position += bytesRequired; } return frame; } /// <summary> /// Constructs an MP3 frame /// </summary> private Mp3Frame() { } /// <summary> /// checks if the four bytes represent a valid header, /// if they are, will parse the values into Mp3Frame /// </summary> private static bool IsValidHeader(byte[] headerBytes, Mp3Frame frame) { if ((headerBytes[0] == 0xFF) && ((headerBytes[1] & 0xE0) == 0xE0)) { // TODO: could do with a bitstream class here frame.MpegVersion = (MpegVersion) ((headerBytes[1] & 0x18) >> 3); if (frame.MpegVersion == MpegVersion.Reserved) { //throw new FormatException("Unsupported MPEG Version"); return false; } frame.MpegLayer = (MpegLayer) ((headerBytes[1] & 0x06) >> 1); if (frame.MpegLayer == MpegLayer.Reserved) { return false; } int layerIndex = frame.MpegLayer == MpegLayer.Layer1 ? 0 : frame.MpegLayer == MpegLayer.Layer2 ? 1 : 2; frame.CrcPresent = (headerBytes[1] & 0x01) == 0x00; frame.BitRateIndex = (headerBytes[2] & 0xF0) >> 4; if (frame.BitRateIndex == 15) { // invalid index return false; } int versionIndex = frame.MpegVersion == Wave.MpegVersion.Version1 ? 0 : 1; frame.BitRate = bitRates[versionIndex, layerIndex, frame.BitRateIndex]*1000; if (frame.BitRate == 0) { return false; } int sampleFrequencyIndex = (headerBytes[2] & 0x0C) >> 2; if (sampleFrequencyIndex == 3) { return false; } if (frame.MpegVersion == MpegVersion.Version1) { frame.SampleRate = sampleRatesVersion1[sampleFrequencyIndex]; } else if (frame.MpegVersion == MpegVersion.Version2) { frame.SampleRate = sampleRatesVersion2[sampleFrequencyIndex]; } else { // mpegVersion == MpegVersion.Version25 frame.SampleRate = sampleRatesVersion25[sampleFrequencyIndex]; } bool padding = (headerBytes[2] & 0x02) == 0x02; bool privateBit = (headerBytes[2] & 0x01) == 0x01; frame.ChannelMode = (ChannelMode) ((headerBytes[3] & 0xC0) >> 6); frame.ChannelExtension = (headerBytes[3] & 0x30) >> 4; frame.Copyright = (headerBytes[3] & 0x08) == 0x08; bool original = (headerBytes[3] & 0x04) == 0x04; int emphasis = (headerBytes[3] & 0x03); int nPadding = padding ? 1 : 0; frame.SampleCount = samplesPerFrame[versionIndex, layerIndex]; int coefficient = frame.SampleCount/8; if (frame.MpegLayer == MpegLayer.Layer1) { frame.FrameLength = (coefficient*frame.BitRate/frame.SampleRate + nPadding)*4; } else { frame.FrameLength = (coefficient*frame.BitRate)/frame.SampleRate + nPadding; } if (frame.FrameLength > MaxFrameLength) { return false; } return true; } return false; } /// <summary> /// Sample rate of this frame /// </summary> public int SampleRate { get; private set; } /// <summary> /// Frame length in bytes /// </summary> public int FrameLength { get; private set; } /// <summary> /// Bit Rate /// </summary> public int BitRate { get; private set; } /// <summary> /// Raw frame data (includes header bytes) /// </summary> public byte[] RawData { get; private set; } /// <summary> /// MPEG Version /// </summary> public MpegVersion MpegVersion { get; private set; } /// <summary> /// MPEG Layer /// </summary> public MpegLayer MpegLayer { get; private set; } /// <summary> /// Channel Mode /// </summary> public ChannelMode ChannelMode { get; private set; } /// <summary> /// The number of samples in this frame /// </summary> public int SampleCount { get; private set; } /// <summary> /// The channel extension bits /// </summary> public int ChannelExtension { get; private set; } /// <summary> /// The bitrate index (directly from the header) /// </summary> public int BitRateIndex { get; private set; } /// <summary> /// Whether the Copyright bit is set /// </summary> public bool Copyright { get; private set; } /// <summary> /// Whether a CRC is present /// </summary> public bool CrcPresent { get; private set; } } }
using System; using System.Threading; namespace CcAcca.CacheAbstraction.Statistics { public abstract class CacheStatistic : ICacheActivityRecorder { #region Member Variables private readonly string _name; #endregion #region Constructors protected CacheStatistic(string name) { _name = name; } #endregion #region Properties public abstract object CurrentValue { get; } public virtual string Name { get { return _name; } } #endregion #region ICacheActivityRecorder Members public virtual void ContainsCalled() {} public virtual void FlushCalled() {} public virtual void ItemAddOrUpdated(string key) {} public virtual void ItemRemoved(string key) {} public virtual void ItemRetrieved(string key) {} public virtual void ItemHit(string key) {} public virtual void ItemMiss(string key) {} #endregion } /// <summary> /// Convenience base class /// </summary> public abstract class AccessTimeCacheStatisticBase : CacheStatistic { protected DateTimeOffset? _when; protected AccessTimeCacheStatisticBase(string name) : base(name) {} public override object CurrentValue { get { return _when; } } } public class CacheHitRatioCacheStatistic : CacheStatistic { public CacheHitRatioCacheStatistic() : base(CacheStatisticsKeys.CacheHitRatio) { } private int _hits; private int _misses; public override void ItemHit(string key) { Interlocked.Increment(ref _hits); } public override void ItemMiss(string key) { Interlocked.Increment(ref _misses); } public override void FlushCalled() { _hits = 0; _misses = 0; } public override object CurrentValue { get { if (Total == 0) return null; return Decimal.Round((decimal)_hits / (Total), 4); } } private int Total { get { return _hits + _misses; } } } public class LastFlushCacheStatistic : AccessTimeCacheStatisticBase { public LastFlushCacheStatistic() : base(CacheStatisticsKeys.LastFlush) { } public override void FlushCalled() { _when = DateTimeOffset.Now; } } /// <summary> /// Records when was the last time the cache was used to add, retrieve or search for an item in the cache /// </summary> public class LastUseCacheStatistic : AccessTimeCacheStatisticBase { public LastUseCacheStatistic() : base(CacheStatisticsKeys.LastUse) {} public override void ContainsCalled() { _when = DateTimeOffset.Now; } public override void FlushCalled() { _when = DateTimeOffset.Now; } public override void ItemAddOrUpdated(string key) { _when = DateTimeOffset.Now; } public override void ItemRetrieved(string key) { _when = DateTimeOffset.Now; } public override void ItemRemoved(string key) { _when = DateTimeOffset.Now; } } /// <summary> /// Records when was the last time the cache was used to add an item to the cache /// </summary> public class LastWrtieCacheStatistic : AccessTimeCacheStatisticBase { public LastWrtieCacheStatistic() : base(CacheStatisticsKeys.LastWrite) {} public override void ItemAddOrUpdated(string key) { _when = DateTimeOffset.Now; } public override void FlushCalled() { _when = null; } public override void ItemRemoved(string key) { _when = DateTimeOffset.Now; } } /// <summary> /// Records when was the last time the cache was used to retrieve an item from the cache /// </summary> public class LastReadCacheStatistic : AccessTimeCacheStatisticBase { public LastReadCacheStatistic() : base(CacheStatisticsKeys.LastRead) {} public override void ContainsCalled() { _when = DateTimeOffset.Now; } public override void FlushCalled() { _when = null; } public override void ItemRetrieved(string key) { _when = DateTimeOffset.Now; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Security.Principal; using Xunit; namespace System.Security.AccessControl.Tests { public class DiscretionaryAcl_AddAccess { public static IEnumerable<object[]> DiscretionaryACL_AddAccess() { yield return new object[] { true, false, 1, "BO", 1, 3, 3, "15:1:1:BA:false:0 ", "15:1:1:BA:false:0#15:1:1:BO:false:0 " }; yield return new object[] { true, false, 0, "BA", 1, 0, 0, "16:0:1:BA:false:0 ", "0:0:1:BA:false:0#16:0:1:BA:false:0 " }; yield return new object[] { true, false, 0, "BA", 1, 0, 0, "0:1:1:BA:false:0 ", "0:1:1:BA:false:0#0:0:1:BA:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 0, 0, "0:0:1:BA:false:0 ", "0:1:1:BA:false:0#0:0:1:BA:false:0 " }; yield return new object[] { true, false, 0, "BA", 2, 2, 2, "0:0:3:BA:false:0 ", "0:0:3:BA:false:0#9:0:2:BA:false:0 " }; yield return new object[] { false, false, 1, "SY", 2, 0, 0, "0:1:1:SY:false:0 ", "0:1:3:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 0, 0, "10:1:1:SY:false:0 ", "2:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 1, 0, "10:1:1:SY:false:0 ", "2:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 1, 1, "10:1:1:SY:false:0 ", "2:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 1, 2, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 1, 3, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 2, 0, "10:1:1:SY:false:0 ", "3:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 2, 1, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0#5:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 2, 2, "10:1:1:SY:false:0 ", "11:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 2, 3, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0#13:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 3, 0, "10:1:1:SY:false:0 ", "3:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 3, 1, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0#7:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 3, 2, "10:1:1:SY:false:0 ", "11:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 3, 3, "10:1:1:SY:false:0 ", "10:1:1:SY:false:0#15:1:1:SY:false:0 " }; yield return new object[] { true, false, 1, "BO", 1, 1, 1, "10:1:1:BA:false:0#10:1:1:BG:false:0#10:1:1:BO:false:0", "10:1:1:BA:false:0#10:1:1:BG:false:0#2:1:1:BO:false:0 " }; yield return new object[] { true, false, 1, "BG", 1, 1, 1, "10:1:1:BA:false:0#10:1:1:BG:false:0#10:1:1:BO:false:0", "10:1:1:BA:false:0#2:1:1:BG:false:0#10:1:1:BO:false:0 " }; yield return new object[] { true, false, 1, "BA", 1, 3, 0, "3:1:1:BA:false:0 ", "3:1:1:BA:false:0 " }; yield return new object[] { true, false, 1, "SY", 1, 3, 3, "9:1:1:SY:false:0 ", "9:1:1:SY:false:0#15:1:1:SY:false:0 " }; } private static bool TestAddAccess(DiscretionaryAcl discretionaryAcl, RawAcl rawAcl, AccessControlType accessControlType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags) { bool result = true; byte[] dAclBinaryForm = null; byte[] rAclBinaryForm = null; discretionaryAcl.AddAccess(accessControlType, sid, accessMask, inheritanceFlags, propagationFlags); if (discretionaryAcl.Count == rawAcl.Count && discretionaryAcl.BinaryLength == rawAcl.BinaryLength) { dAclBinaryForm = new byte[discretionaryAcl.BinaryLength]; rAclBinaryForm = new byte[rawAcl.BinaryLength]; discretionaryAcl.GetBinaryForm(dAclBinaryForm, 0); rawAcl.GetBinaryForm(rAclBinaryForm, 0); if (!Utils.IsBinaryFormEqual(dAclBinaryForm, rAclBinaryForm)) result = false; //redundant index check for (int i = 0; i < discretionaryAcl.Count; i++) { if (!Utils.IsAceEqual(discretionaryAcl[i], rawAcl[i])) { result = false; break; } } } else result = false; return result; } [Theory] [MemberData(nameof(DiscretionaryACL_AddAccess))] public static void AddAccess(bool isContainer, bool isDS, int accessControlType, string sid, int accessMask, int inheritanceFlags, int propagationFlags, string initialRawAclStr, string verifierRawAclStr) { RawAcl rawAcl = Utils.CreateRawAclFromString(initialRawAclStr); DiscretionaryAcl discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); rawAcl = Utils.CreateRawAclFromString(verifierRawAclStr); Assert.True(TestAddAccess(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags)); } [Fact] public static void AddAccess_AdditionalTestCases() { RawAcl rawAcl = null; DiscretionaryAcl discretionaryAcl = null; bool isContainer = false; bool isDS = false; int accessControlType = 0; string sid = null; int accessMask = 1; int inheritanceFlags = 0; int propagationFlags = 0; GenericAce gAce = null; byte[] opaque = null; //Case 1, non-Container, but InheritanceFlags is not None AssertExtensions.Throws<ArgumentException>("inheritanceFlags", () => { isContainer = false; isDS = false; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG")), 1, InheritanceFlags.ContainerInherit, PropagationFlags.None); }); //Case 2, non-Container, but PropagationFlags is not None AssertExtensions.Throws<ArgumentException>("propagationFlags", () => { isContainer = false; isDS = false; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG")), 1, InheritanceFlags.None, PropagationFlags.InheritOnly); }); //Case 3, Container, InheritanceFlags is None, PropagationFlags is InheritOnly AssertExtensions.Throws<ArgumentException>("propagationFlags", () => { isContainer = true; isDS = false; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG")), 1, InheritanceFlags.None, PropagationFlags.InheritOnly); }); //Case 4, Container, InheritanceFlags is None, PropagationFlags is NoPropagateInherit AssertExtensions.Throws<ArgumentException>("propagationFlags", () => { isContainer = true; isDS = false; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG")), 1, InheritanceFlags.None, PropagationFlags.NoPropagateInherit); }); //Case 5, Container, InheritanceFlags is None, PropagationFlags is NoPropagateInherit | InheritOnly AssertExtensions.Throws<ArgumentException>("propagationFlags", () => { isContainer = true; isDS = false; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess(AccessControlType.Allow, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid("BG")), 1, InheritanceFlags.None, PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly); }); //Case 6, accessMask = 0 AssertExtensions.Throws<ArgumentException>("accessMask", () => { isContainer = true; isDS = false; accessControlType = 1; sid = "BA"; accessMask = 0; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess((AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 7, null sid Assert.Throws<ArgumentNullException>(() => { isContainer = true; isDS = false; accessControlType = 1; accessMask = 1; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess((AccessControlType)accessControlType, null, accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 8, add one Access ACE to the DiscretionaryAcl with no ACE isContainer = true; isDS = false; accessControlType = 0; sid = "BA"; accessMask = 1; inheritanceFlags = 3; propagationFlags = 3; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); //15 = AceFlags.ObjectInherit |AceFlags.ContainerInherit | AceFlags.NoPropagateInherit | AceFlags.InheritOnly gAce = new CommonAce((AceFlags)15, AceQualifier.AccessAllowed, accessMask, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(rawAcl.Count, gAce); Assert.True(TestAddAccess(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags)) ; //Case 9, Container, InheritOnly ON, but ContainerInherit and ObjectInherit are both OFF //add meaningless Access ACE to the DiscretionaryAcl with no ACE, ace should not //be added. There are mutiple type of meaningless Ace, but as both AddAccess and Constructor3 //call the same method to check the meaninglessness, only some sanitory cases are enough. //bug# 288116 AssertExtensions.Throws<ArgumentException>("propagationFlags", () => { isContainer = true; isDS = false; inheritanceFlags = 0;//InheritanceFlags.None propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 0; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); TestAddAccess(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 10, add Ace of NOT(AccessControlType.Allow |AccessControlType.Denied) to the DiscretionaryAcl with no ACE, // should throw appropriate exception for wrong parameter, bug#287188 Assert.Throws<ArgumentOutOfRangeException>(() => { isContainer = true; isDS = false; inheritanceFlags = 1;//InheritanceFlags.ContainerInherit propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 100; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); discretionaryAcl.AddAccess((AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 11, all the ACEs in the Dacl are non-qualified ACE, no merge Assert.Throws<InvalidOperationException>(() => { isContainer = true; isDS = false; inheritanceFlags = 1;//InheritanceFlags.ContainerInherit propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 0; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); opaque = new byte[4]; gAce = new CustomAce(AceType.MaxDefinedAceType + 1, AceFlags.InheritanceFlags, opaque); ; rawAcl.InsertAce(0, gAce); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); gAce = new CommonAce(AceFlags.ContainerInherit | AceFlags.InheritOnly, AceQualifier.AccessAllowed, accessMask, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), false, null); rawAcl.InsertAce(0, gAce); //After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and //forbid the modification on uncanonical ACL, this case will throw InvalidOperationException TestAddAccess(discretionaryAcl, rawAcl, (AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); //Case 12, add Ace to exceed binary length boundary, throw exception isContainer = true; isDS = false; inheritanceFlags = 1;//InheritanceFlags.ContainerInherit propagationFlags = 2; //PropagationFlags.InheritOnly accessControlType = 0; sid = "BA"; accessMask = 1; rawAcl = new RawAcl(0, 1); opaque = new byte[GenericAcl.MaxBinaryLength + 1 - 8 - 4 - 16]; gAce = new CustomAce(AceType.MaxDefinedAceType + 1, AceFlags.InheritanceFlags, opaque); ; rawAcl.InsertAce(0, gAce); discretionaryAcl = new DiscretionaryAcl(isContainer, isDS, rawAcl); //After Mark changes design to make ACL with any CustomAce, CompoundAce uncanonical and //forbid the modification on uncanonical ACL, this case will throw InvalidOperationException Assert.Throws<InvalidOperationException>(() => { discretionaryAcl.AddAccess((AccessControlType)accessControlType, new SecurityIdentifier(Utils.TranslateStringConstFormatSidToStandardFormatSid(sid)), accessMask, (InheritanceFlags)inheritanceFlags, (PropagationFlags)propagationFlags); }); } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFAB_STATIC_API using System; using System.Collections.Generic; using PlayFab.ExperimentationModels; using PlayFab.Internal; namespace PlayFab { /// <summary> /// APIs for managing experiments. /// </summary> public static class PlayFabExperimentationAPI { static PlayFabExperimentationAPI() {} /// <summary> /// Verify entity login. /// </summary> public static bool IsEntityLoggedIn() { return PlayFabSettings.staticPlayer.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabSettings.staticPlayer.ForgetAllCredentials(); } /// <summary> /// Creates a new experiment exclusion group for a title. /// </summary> public static void CreateExclusionGroup(CreateExclusionGroupRequest request, Action<CreateExclusionGroupResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/CreateExclusionGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Creates a new experiment for a title. /// </summary> public static void CreateExperiment(CreateExperimentRequest request, Action<CreateExperimentResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/CreateExperiment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Deletes an existing exclusion group for a title. /// </summary> public static void DeleteExclusionGroup(DeleteExclusionGroupRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/DeleteExclusionGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Deletes an existing experiment for a title. /// </summary> public static void DeleteExperiment(DeleteExperimentRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/DeleteExperiment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Gets the details of all exclusion groups for a title. /// </summary> public static void GetExclusionGroups(GetExclusionGroupsRequest request, Action<GetExclusionGroupsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/GetExclusionGroups", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Gets the details of all exclusion groups for a title. /// </summary> public static void GetExclusionGroupTraffic(GetExclusionGroupTrafficRequest request, Action<GetExclusionGroupTrafficResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/GetExclusionGroupTraffic", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Gets the details of all experiments for a title. /// </summary> public static void GetExperiments(GetExperimentsRequest request, Action<GetExperimentsResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/GetExperiments", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Gets the latest scorecard of the experiment for the title. /// </summary> public static void GetLatestScorecard(GetLatestScorecardRequest request, Action<GetLatestScorecardResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/GetLatestScorecard", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Gets the treatment assignments for a player for every running experiment in the title. /// </summary> public static void GetTreatmentAssignment(GetTreatmentAssignmentRequest request, Action<GetTreatmentAssignmentResult> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/GetTreatmentAssignment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Starts an existing experiment for a title. /// </summary> public static void StartExperiment(StartExperimentRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/StartExperiment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Stops an existing experiment for a title. /// </summary> public static void StopExperiment(StopExperimentRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/StopExperiment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Updates an existing exclusion group for a title. /// </summary> public static void UpdateExclusionGroup(UpdateExclusionGroupRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/UpdateExclusionGroup", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } /// <summary> /// Updates an existing experiment for a title. /// </summary> public static void UpdateExperiment(UpdateExperimentRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null) { var context = (request == null ? null : request.AuthenticationContext) ?? PlayFabSettings.staticPlayer; var callSettings = PlayFabSettings.staticSettings; if (!context.IsEntityLoggedIn()) throw new PlayFabException(PlayFabExceptionCode.NotLoggedIn,"Must be logged in to call this method"); PlayFabHttp.MakeApiCall("/Experimentation/UpdateExperiment", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders, context, callSettings); } } } #endif
#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.BusinessEntities.BusinessEntities File: MarketDepth.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.BusinessEntities { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Ecng.Collections; using Ecng.Common; using MoreLinq; using StockSharp.Messages; using StockSharp.Localization; /// <summary> /// Order book. /// </summary> [System.Runtime.Serialization.DataContract] [Serializable] //[EntityFactory(typeof(UnitializedEntityFactory<MarketDepth>))] public class MarketDepth : Cloneable<MarketDepth>, IEnumerable<Quote>, ISynchronizedCollection { private readonly SyncObject _syncRoot = new SyncObject(); /// <summary> /// Create order book. /// </summary> /// <param name="security">Security.</param> public MarketDepth(Security security) { if (ReferenceEquals(security, null)) throw new ArgumentNullException(nameof(security)); Security = security; _bids = _asks = ArrayHelper.Empty<Quote>(); } private int _maxDepth = 100; /// <summary> /// The maximum depth of order book. /// </summary> /// <remarks> /// The default value is 100. If the exceeded the maximum depth the event <see cref="MarketDepth.QuoteOutOfDepth"/> will triggered. /// </remarks> public int MaxDepth { get { return _maxDepth; } set { if (value < 1) throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.Str480); _maxDepth = value; Truncate(Bids, Asks, default(DateTimeOffset)); } } /// <summary> /// Security. /// </summary> public Security Security { get; } //[field: NonSerialized] //private IConnector _connector; ///// <summary> ///// Connection to the trading system. ///// </summary> //[Ignore] //[XmlIgnore] //[Obsolete("The property Connector was obsoleted and is always null.")] //public IConnector Connector //{ // get { return _connector; } // set { _connector = value; } //} /// <summary> /// Automatically check for quotes by <see cref="Verify()"/>. /// </summary> /// <remarks> /// The default is disabled for performance. /// </remarks> public bool AutoVerify { get; set; } /// <summary> /// Whether to use aggregated quotes <see cref="AggregatedQuote"/> at the join of the volumes with the same price. /// </summary> /// <remarks> /// The default is disabled for performance. /// </remarks> public bool UseAggregatedQuotes { get; set; } /// <summary> /// Last change time. /// </summary> public DateTimeOffset LastChangeTime { get; set; } /// <summary> /// The order book local time stamp. /// </summary> public DateTimeOffset LocalTime { get; set; } // TODO //private Quote[] _bidsCache; private Quote[] _bids; /// <summary> /// Get the array of bids sorted by descending price. The first (best) bid will be the maximum price. /// </summary> public Quote[] Bids { get { return _bids; //lock (_syncRoot) //{ // return _bidsCache ?? (_bidsCache = _bids.Select(q => q.Clone()).ToArray()); //} } private set { if (value == null) throw new ArgumentNullException(nameof(value)); _bids = value; //_bidsCache = null; } } //private Quote[] _asksCache; private Quote[] _asks; /// <summary> /// Get the array of asks sorted by ascending price. The first (best) ask will be the minimum price. /// </summary> public Quote[] Asks { get { return _asks; //lock (_syncRoot) //{ // return _asksCache ?? (_asksCache = _asks.Select(q => q.Clone()).ToArray()); //} } private set { if (value == null) throw new ArgumentNullException(nameof(value)); _asks = value; //_asksCache = null; } } /// <summary> /// Trading security currency. /// </summary> public CurrencyTypes? Currency { get; set; } /// <summary> /// The best bid. If the order book does not contain bids, will be returned <see langword="null" />. /// </summary> public Quote BestBid { get; private set; } /// <summary> /// The best ask. If the order book does not contain asks, will be returned <see langword="null" />. /// </summary> public Quote BestAsk { get; private set; } /// <summary> /// The best pair. If the order book is empty, will be returned <see langword="null" />. /// </summary> public MarketDepthPair BestPair => GetPair(0); /// <summary> /// To get the total price size by bids. /// </summary> public decimal TotalBidsPrice { get { lock (_syncRoot) return _bids.Length > 0 ? Security.ShrinkPrice(_bids.Sum(b => b.Price)) : 0; } } /// <summary> /// To get the total price size by offers. /// </summary> public decimal TotalAsksPrice { get { lock (_syncRoot) return _asks.Length > 0 ? Security.ShrinkPrice(_asks.Sum(a => a.Price)) : 0; } } /// <summary> /// Get bids total volume. /// </summary> public decimal TotalBidsVolume { get { lock (_syncRoot) return _bids.Sum(b => b.Volume); } } /// <summary> /// Get asks total volume. /// </summary> public decimal TotalAsksVolume { get { lock (_syncRoot) return _asks.Sum(a => a.Volume); } } /// <summary> /// Get total volume. /// </summary> public decimal TotalVolume { get { lock (_syncRoot) return TotalBidsVolume + TotalAsksVolume; } } /// <summary> /// To get the total price size. /// </summary> public decimal TotalPrice { get { lock (_syncRoot) return TotalBidsPrice + TotalAsksPrice; } } /// <summary> /// Total quotes count (bids + asks). /// </summary> public int Count { get { lock (_syncRoot) return _bids.Length + _asks.Length; } } private int _depth; /// <summary> /// Depth of book. /// </summary> public int Depth { get { return _depth; } private set { if (_depth == value) return; _depth = value; DepthChanged?.Invoke(); } } /// <summary> /// Event on exceeding the maximum allowable depth of quotes. /// </summary> public event Action<Quote> QuoteOutOfDepth; /// <summary> /// Depth <see cref="MarketDepth.Depth"/> changed. /// </summary> public event Action DepthChanged; /// <summary> /// Quotes changed. /// </summary> public event Action QuotesChanged; /// <summary> /// To reduce the order book to the required depth. /// </summary> /// <param name="newDepth">New order book depth.</param> public void Decrease(int newDepth) { var currentDepth = Depth; if (newDepth < 0) throw new ArgumentOutOfRangeException(nameof(newDepth), newDepth, LocalizedStrings.Str481); else if (newDepth > currentDepth) throw new ArgumentOutOfRangeException(nameof(newDepth), newDepth, LocalizedStrings.Str482Params.Put(currentDepth)); lock (_syncRoot) { Bids = Decrease(_bids, newDepth); Asks = Decrease(_asks, newDepth); UpdateDepthAndTime(); } RaiseQuotesChanged(); } private static Quote[] Decrease(Quote[] quotes, int newDepth) { if (quotes == null) throw new ArgumentNullException(nameof(quotes)); if (newDepth <= quotes.Length) Array.Resize(ref quotes, newDepth); return quotes; } /// <summary> /// To get a quote by the direction <see cref="Sides"/> and the depth index. /// </summary> /// <param name="orderDirection">Orders side.</param> /// <param name="depthIndex">Depth index. Zero index means the best quote.</param> /// <returns>Quote. If a quote does not exist for specified depth, then the <see langword="null" /> will be returned.</returns> public Quote GetQuote(Sides orderDirection, int depthIndex) { lock (_syncRoot) return GetQuotesInternal(orderDirection).ElementAtOrDefault(depthIndex); } /// <summary> /// To get a quote by the price. /// </summary> /// <param name="price">Quote price.</param> /// <returns>Found quote. If there is no quote in the order book for the passed price, then the <see langword="null" /> will be returned.</returns> public Quote GetQuote(decimal price) { var quotes = GetQuotes(price); var i = GetQuoteIndex(quotes, price); return i < 0 ? null : quotes[i]; } /// <summary> /// To get quotes by the direction <see cref="Sides"/>. /// </summary> /// <param name="orderDirection">Orders side.</param> /// <returns>Quotes.</returns> public Quote[] GetQuotes(Sides orderDirection) { return orderDirection == Sides.Buy ? Bids : Asks; } /// <summary> /// To get the best quote by the direction <see cref="Sides"/>. /// </summary> /// <param name="orderDirection">Order side.</param> /// <returns>The best quote. If the order book is empty, then the <see langword="null" /> will be returned.</returns> public Quote GetBestQuote(Sides orderDirection) { return orderDirection == Sides.Buy ? BestBid : BestAsk; } /// <summary> /// To get a pair of quotes (bid + offer) by the depth index. /// </summary> /// <param name="depthIndex">Depth index. Zero index means the best pair of quotes.</param> /// <returns>The pair of quotes. If the index is larger than book order depth <see cref="MarketDepth.Depth"/>, then the <see langword="null" /> is returned.</returns> public MarketDepthPair GetPair(int depthIndex) { if (depthIndex < 0) throw new ArgumentOutOfRangeException(nameof(depthIndex), depthIndex, LocalizedStrings.Str483); lock (_syncRoot) { var bid = GetQuote(Sides.Buy, depthIndex); var ask = GetQuote(Sides.Sell, depthIndex); if (bid == null && ask == null) return null; return new MarketDepthPair(Security, bid, ask); } } /// <summary> /// To get a pair of quotes for a given book depth. /// </summary> /// <param name="depth">Book depth. The counting is from the best quotes.</param> /// <returns>Spread.</returns> public IEnumerable<MarketDepthPair> GetTopPairs(int depth) { if (depth < 0) throw new ArgumentOutOfRangeException(nameof(depth), depth, LocalizedStrings.Str484); var retVal = new List<MarketDepthPair>(); lock (_syncRoot) { for (var i = 0; i < depth; i++) { var single = GetPair(i); if (single != null) retVal.Add(single); else break; } } return retVal; } /// <summary> /// To get quotes for a given book depth. /// </summary> /// <param name="depth">Book depth. Quotes are in order of price increasing from bids to offers.</param> /// <returns>Spread.</returns> public IEnumerable<Quote> GetTopQuotes(int depth) { if (depth < 0) throw new ArgumentOutOfRangeException(nameof(depth), depth, LocalizedStrings.Str484); var retVal = new List<Quote>(); lock (_syncRoot) { for (var i = depth - 1; i >= 0; i--) { var single = GetQuote(Sides.Buy, i); if (single != null) retVal.Add(single); } for (var i = 0; i < depth; i++) { var single = GetQuote(Sides.Sell, i); if (single != null) retVal.Add(single); else break; } } return retVal; } /// <summary> /// Update the order book by new quotes. /// </summary> /// <param name="quotes">The new quotes.</param> /// <param name="lastChangeTime">Last change time.</param> /// <returns>Market depth.</returns> /// <remarks> /// The old quotes will be removed from the book. /// </remarks> public MarketDepth Update(IEnumerable<Quote> quotes, DateTimeOffset lastChangeTime = default(DateTimeOffset)) { if (quotes == null) throw new ArgumentNullException(nameof(quotes)); var bids = Enumerable.Empty<Quote>(); var asks = Enumerable.Empty<Quote>(); foreach (var group in quotes.GroupBy(q => q.OrderDirection)) { if (group.Key == Sides.Buy) bids = group; else asks = group; } return Update(bids, asks, false, lastChangeTime); } /// <summary> /// Update the order book by new bids and asks. /// </summary> /// <param name="bids">The new bids.</param> /// <param name="asks">The new asks.</param> /// <param name="isSorted">Are quotes sorted. This parameter is used for optimization in order to prevent re-sorting.</param> /// <param name="lastChangeTime">Last change time.</param> /// <returns>Market depth.</returns> /// <remarks> /// The old quotes will be removed from the book. /// </remarks> public MarketDepth Update(IEnumerable<Quote> bids, IEnumerable<Quote> asks, bool isSorted = false, DateTimeOffset lastChangeTime = default(DateTimeOffset)) { if (bids == null) throw new ArgumentNullException(nameof(bids)); if (asks == null) throw new ArgumentNullException(nameof(asks)); if (!isSorted) { bids = bids.OrderBy(q => 0 - q.Price); asks = asks.OrderBy(q => q.Price); } bids = bids.ToArray(); asks = asks.ToArray(); if (AutoVerify) { if (!Verify(bids, asks)) throw new ArgumentException(LocalizedStrings.Str485); } Truncate((Quote[])bids, (Quote[])asks, lastChangeTime); return this; } private void Truncate(Quote[] bids, Quote[] asks, DateTimeOffset lastChangeTime) { Quote[] outOfRangeBids; Quote[] outOfRangeAsks; lock (_syncRoot) { Update(Truncate(bids, out outOfRangeBids), Truncate(asks, out outOfRangeAsks), lastChangeTime); } var evt = QuoteOutOfDepth; if (evt != null) { if (outOfRangeBids != null) outOfRangeBids.ForEach(evt); if (outOfRangeAsks != null) outOfRangeAsks.ForEach(evt); } } private Quote[] Truncate(Quote[] quotes, out Quote[] outOfRangeQuotes) { if (quotes.Length > MaxDepth) { outOfRangeQuotes = new Quote[quotes.Length - MaxDepth]; Array.Copy(quotes, MaxDepth, outOfRangeQuotes, 0, outOfRangeQuotes.Length); Array.Resize(ref quotes, MaxDepth); } else { outOfRangeQuotes = null; } return quotes; } /// <summary> /// To update the order book. The version without checks and blockings. /// </summary> /// <param name="bids">Sorted bids.</param> /// <param name="asks">Sorted asks.</param> /// <param name="lastChangeTime">Change time.</param> public void Update(Quote[] bids, Quote[] asks, DateTimeOffset lastChangeTime) { //_bidsCache = null; //_asksCache = null; _bids = bids; _asks = asks; UpdateDepthAndTime(lastChangeTime, false); if (null != QuotesChanged) QuotesChanged(); //RaiseQuotesChanged(); } /// <summary> /// To refresh the quote. If a quote with the same price is already in the order book, it is updated as passed. Otherwise, it automatically rebuilds the order book. /// </summary> /// <param name="quote">The new quote.</param> public void UpdateQuote(Quote quote) { SetQuote(quote, false); } /// <summary> /// Add buy quote. /// </summary> /// <param name="price">Buy price.</param> /// <param name="volume">Buy volume.</param> public void AddBid(decimal price, decimal volume) { AddQuote(new Quote { Security = Security, Price = price, Volume = volume, OrderDirection = Sides.Buy, }); } /// <summary> /// Add sell quote. /// </summary> /// <param name="price">Sell price.</param> /// <param name="volume">Sell volume.</param> public void AddAsk(decimal price, decimal volume) { AddQuote(new Quote { Security = Security, Price = price, Volume = volume, OrderDirection = Sides.Sell, }); } /// <summary> /// To add the quote. If a quote with the same price is already in the order book, they are combined into the <see cref="AggregatedQuote"/>. /// </summary> /// <param name="quote">The new quote.</param> public void AddQuote(Quote quote) { SetQuote(quote, true); } private void SetQuote(Quote quote, bool isAggregate) { CheckQuote(quote); Quote outOfDepthQuote = null; lock (_syncRoot) { var quotes = GetQuotes(quote.OrderDirection); var index = GetQuoteIndex(quotes, quote.Price); if (index != -1) { if (isAggregate) { var existedQuote = quotes[index]; if (UseAggregatedQuotes) { var aggQuote = existedQuote as AggregatedQuote; if (aggQuote == null) { aggQuote = new AggregatedQuote { Price = quote.Price, Security = quote.Security, OrderDirection = quote.OrderDirection }; aggQuote.InnerQuotes.Add(existedQuote); quotes[index] = aggQuote; } aggQuote.InnerQuotes.Add(quote); } else existedQuote.Volume += quote.Volume; } else { quotes[index] = quote; } } else { for (index = 0; index < quotes.Length; index++) { var currentPrice = quotes[index].Price; if (quote.OrderDirection == Sides.Buy) { if (quote.Price > currentPrice) break; } else { if (quote.Price < currentPrice) break; } } Array.Resize(ref quotes, quotes.Length + 1); if (index < (quotes.Length - 1)) Array.Copy(quotes, index, quotes, index + 1, quotes.Length - 1 - index); quotes[index] = quote; if (quotes.Length > MaxDepth) { outOfDepthQuote = quotes[quotes.Length - 1]; quotes = RemoveAt(quotes, quotes.Length - 1); } if (quote.OrderDirection == Sides.Buy) Bids = quotes; else Asks = quotes; } UpdateDepthAndTime(); if (quotes.Length > MaxDepth) throw new InvalidOperationException(LocalizedStrings.Str486Params.Put(MaxDepth, quotes.Length)); } RaiseQuotesChanged(); if (outOfDepthQuote != null) QuoteOutOfDepth?.Invoke(outOfDepthQuote); } #region IEnumerable<Quote> /// <summary> /// To get the enumerator object. /// </summary> /// <returns>The enumerator object.</returns> public IEnumerator<Quote> GetEnumerator() { return this.SyncGet(c => Bids.Reverse().Concat(Asks)).Cast<Quote>().GetEnumerator(); } /// <summary> /// To get the enumerator object. /// </summary> /// <returns>The enumerator object.</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion /// <summary> /// To get all pairs from the order book. /// </summary> /// <returns>Pairs from which the order book is composed.</returns> public IEnumerable<MarketDepthPair> ToPairs() { return GetTopPairs(Depth); } /// <summary> /// Remove the quote. /// </summary> /// <param name="quote">The quote to remove.</param> /// <param name="lastChangeTime">Order book change time.</param> public void Remove(Quote quote, DateTimeOffset lastChangeTime = default(DateTimeOffset)) { if (quote == null) throw new ArgumentNullException(nameof(quote)); Remove(quote.OrderDirection, quote.Price, quote.Volume, lastChangeTime); } /// <summary> /// Remove the volume for the price. /// </summary> /// <param name="price">Remove the quote for the price.</param> /// <param name="volume">The volume to be deleted. If it is not specified, then all the quote is removed.</param> /// <param name="lastChangeTime">Order book change time.</param> public void Remove(decimal price, decimal volume = 0, DateTimeOffset lastChangeTime = default(DateTimeOffset)) { lock (_syncRoot) { var dir = GetDirection(price); if (dir == null) throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str487); Remove((Sides)dir, price, volume, lastChangeTime); } } /// <summary> /// Remove the volume for the price. /// </summary> /// <param name="direction">Order side.</param> /// <param name="price">Remove the quote for the price.</param> /// <param name="volume">The volume to be deleted. If it is not specified, then all the quote is removed.</param> /// <param name="lastChangeTime">Order book change time.</param> public void Remove(Sides direction, decimal price, decimal volume = 0, DateTimeOffset lastChangeTime = default(DateTimeOffset)) { if (price <= 0) throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str488); if (volume < 0) throw new ArgumentOutOfRangeException(nameof(volume), volume, LocalizedStrings.Str489); lock (_syncRoot) { var quotes = GetQuotesInternal(direction); var index = GetQuoteIndex(quotes, price); if (index == -1) throw new ArgumentOutOfRangeException(nameof(price), price, LocalizedStrings.Str487); var quote = quotes[index]; decimal leftVolume; if (volume > 0) { if (quote.Volume < volume) throw new ArgumentOutOfRangeException(nameof(volume), volume, LocalizedStrings.Str490Params.Put(quote)); leftVolume = quote.Volume - volume; if (UseAggregatedQuotes) { var aggQuote = quote as AggregatedQuote; if (aggQuote != null) { while (volume > 0) { var innerQuote = aggQuote.InnerQuotes.First(); if (innerQuote.Volume > volume) { innerQuote.Volume -= volume; break; } else { aggQuote.InnerQuotes.Remove(innerQuote); volume -= innerQuote.Volume; } } } } } else leftVolume = 0; if (leftVolume == 0) { quotes = RemoveAt(quotes, index); if (quote.OrderDirection == Sides.Buy) Bids = quotes; else Asks = quotes; UpdateDepthAndTime(lastChangeTime); } else { quote.Volume = leftVolume; UpdateTime(lastChangeTime); } } RaiseQuotesChanged(); } private static Quote[] RemoveAt(Quote[] quotes, int index) { var newQuotes = new Quote[quotes.Length - 1]; if (index > 0) Array.Copy(quotes, 0, newQuotes, 0, index); if (index < (quotes.Length - 1)) Array.Copy(quotes, index + 1, newQuotes, index, quotes.Length - index - 1); return newQuotes; } private static int GetQuoteIndex(Quote[] quotes, decimal price) { var stop = quotes.Length - 1; if (stop < 0) return -1; var first = quotes[0]; var cmp = decimal.Compare(price, first.Price); if (cmp == 0) return 0; var last = quotes[stop]; var desc = first.Price - last.Price > 0m; if (desc) cmp = -cmp; if (cmp < 0) return -1; cmp = decimal.Compare(price, last.Price); if (desc) cmp = -cmp; if (cmp > 0) return -1; if (cmp == 0) return stop; var start = 0; while (stop - start >= 0) { var mid = (start + stop) >> 1; cmp = decimal.Compare(price, quotes[mid].Price); if (desc) cmp = -cmp; if (cmp > 0) start = mid + 1; else if (cmp < 0) stop = mid - 1; else return mid; } return -1; } private Quote[] GetQuotesInternal(Sides direction) { return direction == Sides.Buy ? _bids : _asks; } private Quote[] GetQuotes(decimal price) { var dir = GetDirection(price); if (dir == null) return ArrayHelper.Empty<Quote>(); else return dir == Sides.Buy ? _bids : _asks; } private Sides? GetDirection(decimal price) { if (!ReferenceEquals(BestBid, null) && BestBid.Price >= price) return Sides.Buy; else if (!ReferenceEquals(BestAsk, null) && BestAsk.Price <= price) return Sides.Sell; else return null; } private void CheckQuote(Quote quote) { if (quote == null) throw new ArgumentNullException(nameof(quote)); if (quote.Security != null && quote.Security != Security) throw new ArgumentException(LocalizedStrings.Str491Params.Put(quote.Security.Id, Security.Id), nameof(quote)); if (quote.Security == null) quote.Security = Security; if (quote.Price <= 0) throw new ArgumentOutOfRangeException(nameof(quote), quote.Price, LocalizedStrings.Str488); if (quote.Volume < 0) throw new ArgumentOutOfRangeException(nameof(quote), quote.Volume, LocalizedStrings.Str489); } private void UpdateDepthAndTime(DateTimeOffset lastChangeTime = default(DateTimeOffset), bool depthChangedEventNeeded = true) { if (depthChangedEventNeeded) { Depth = _bids.Length > _asks.Length ? _bids.Length : _asks.Length; } else { _depth = _bids.Length > _asks.Length ? _bids.Length : _asks.Length; } BestBid = _bids.Length > 0 ? _bids[0] : null; BestAsk = _asks.Length > 0 ? _asks[0] : null; UpdateTime(lastChangeTime); } private void UpdateTime(DateTimeOffset lastChangeTime) { if (lastChangeTime != default(DateTimeOffset)) { LastChangeTime = lastChangeTime; } } private void RaiseQuotesChanged() { QuotesChanged?.Invoke(); } /// <summary> /// Create a copy of <see cref="MarketDepth"/>. /// </summary> /// <returns>Copy.</returns> public override MarketDepth Clone() { var clone = new MarketDepth(Security) { MaxDepth = MaxDepth, UseAggregatedQuotes = UseAggregatedQuotes, AutoVerify = AutoVerify, Currency = Currency, }; lock (_syncRoot) { clone.Update(_bids.Select(q => q.Clone()), _asks.Select(q => q.Clone()), true, LastChangeTime); clone.LocalTime = LocalTime; } return clone; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> public override string ToString() { return this.Select(q => q.ToString()).Join(Environment.NewLine); } /// <summary> /// To determine whether the order book is in the right state. /// </summary> /// <returns><see langword="true" />, if the order book contains correct data, otherwise <see langword="false" />.</returns> /// <remarks> /// It is used in cases when the trading system by mistake sends the wrong quotes. /// </remarks> public bool Verify() { lock (_syncRoot) return Verify(_bids, _asks); } private bool Verify(IEnumerable<Quote> bids, IEnumerable<Quote> asks) { var bestBid = bids.FirstOrDefault(); var bestAsk = asks.FirstOrDefault(); if (bestBid != null && bestAsk != null) { return bids.All(b => b.Price < bestAsk.Price) && asks.All(a => a.Price > bestBid.Price) && Verify(bids, true) && Verify(asks, false); } else { return Verify(bids, true) && Verify(asks, false); } } private bool Verify(IEnumerable<Quote> quotes, bool isBids) { if (quotes.IsEmpty()) return true; if (quotes.Any(q => !Verify(q, isBids))) return false; if (quotes.GroupBy(q => q.Price).Any(g => g.Count() > 1)) return false; var prev = quotes.First(); foreach (var current in quotes.Skip(1)) { if (isBids) { if (current.Price > prev.Price) return false; } else { if (current.Price < prev.Price) return false; } prev = current; } return true; } private bool Verify(Quote quote, bool isBids) { if (quote == null) throw new ArgumentNullException(nameof(quote)); return quote.Price > 0 && quote.Volume > 0 && quote.OrderDirection == (isBids ? Sides.Buy : Sides.Sell) && quote.Security == Security; } SyncObject ISynchronizedCollection.SyncRoot => _syncRoot; } }
using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.ClassBased; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.MappingModel.Output; using FluentNHibernate.Testing.Testing; using NUnit.Framework; namespace FluentNHibernate.Testing.MappingModel.Output { [TestFixture] public class XmlReferenceComponentWriterTester { private IXmlWriter<ReferenceComponentMapping> writer; [SetUp] public void GetWriterFromContainer() { var container = new XmlWriterContainer(); writer = container.Resolve<IXmlWriter<ReferenceComponentMapping>>(); } [Test] public void ShouldWriteNameAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Name, "name").MapsToAttribute("name"); testHelper.VerifyAll(writer); } private XmlWriterTestHelper<ReferenceComponentMapping> CreateTestHelper() { var testHelper = new XmlWriterTestHelper<ReferenceComponentMapping>(); testHelper.CreateInstance(CreateInstance); return testHelper; } private ReferenceComponentMapping CreateInstance() { var property = new DummyPropertyInfo("ComponentProperty", typeof(ComponentTarget)).ToMember(); var instance = new ReferenceComponentMapping(ComponentType.Component, property, typeof(ComponentTarget), typeof(Target), null); instance.AssociateExternalMapping(new ExternalComponentMapping(ComponentType.Component)); return instance; } [Test] public void ShouldWriteAccessAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Access, "acc").MapsToAttribute("access"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteClassAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Class, new TypeReference("class")).MapsToAttribute("class"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteUpdateAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Update, true).MapsToAttribute("update"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteInsertAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Insert, true).MapsToAttribute("insert"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteLazyAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.Lazy, true).MapsToAttribute("lazy"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteOptimisticLockAttribute() { var testHelper = CreateTestHelper(); testHelper.Check(x => x.OptimisticLock, true).MapsToAttribute("optimistic-lock"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteComponents() { var mapping = CreateInstance(); mapping.AddComponent(new ComponentMapping(ComponentType.Component)); writer.VerifyXml(mapping) .Element("component").Exists(); } [Test] public void ShouldWriteDynamicComponents() { var mapping = CreateInstance(); mapping.AddComponent(new ComponentMapping(ComponentType.DynamicComponent)); writer.VerifyXml(mapping) .Element("dynamic-component").Exists(); } [Test] public void ShouldWriteProperties() { var mapping = CreateInstance(); mapping.AddProperty(new PropertyMapping()); writer.VerifyXml(mapping) .Element("property").Exists(); } [Test] public void ShouldWriteManyToOnes() { var mapping = CreateInstance(); mapping.AddReference(new ManyToOneMapping()); writer.VerifyXml(mapping) .Element("many-to-one").Exists(); } [Test] public void ShouldWriteOneToOnes() { var mapping = CreateInstance(); mapping.AddOneToOne(new OneToOneMapping()); writer.VerifyXml(mapping) .Element("one-to-one").Exists(); } [Test] public void ShouldWriteAnys() { var mapping = CreateInstance(); mapping.AddAny(new AnyMapping()); writer.VerifyXml(mapping) .Element("any").Exists(); } [Test] public void ShouldWriteMaps() { var mapping = CreateInstance(); mapping.AddCollection(CollectionMapping.Map()); writer.VerifyXml(mapping) .Element("map").Exists(); } [Test] public void ShouldWriteSets() { var mapping = CreateInstance(); mapping.AddCollection(CollectionMapping.Set()); writer.VerifyXml(mapping) .Element("set").Exists(); } [Test] public void ShouldWriteBags() { var mapping = CreateInstance(); mapping.AddCollection(CollectionMapping.Bag()); writer.VerifyXml(mapping) .Element("bag").Exists(); } [Test] public void ShouldWriteLists() { var mapping = CreateInstance(); mapping.AddCollection(CollectionMapping.List()); writer.VerifyXml(mapping) .Element("list").Exists(); } [Test, Ignore("Ignore ShouldWriteArrays")] public void ShouldWriteArrays() { Assert.Fail(); } [Test, Ignore("Ignore ShouldWritePrimitiveArrays")] public void ShouldWritePrimitiveArrays() { Assert.Fail(); } private class Target {} private class ComponentTarget {} } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// VirtualNetworkGatewayConnectionsOperations operations. /// </summary> public partial interface IVirtualNetworkGatewayConnectionsOperations { /// <summary> /// Creates or updates a virtual network gateway connection in the /// specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the specified virtual network gateway connection by resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual /// network gateway connection in the specified resource group through /// Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway /// connection Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> SetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Get VirtualNetworkGatewayConnectionSharedKey operation /// retrieves information about the specified virtual network gateway /// connection shared key through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection shared key name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> GetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all /// the virtual network gateways connections created. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets /// the virtual network gateway connection shared key for passed /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway /// connection shared key operation through network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionResetSharedKey>> ResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates a virtual network gateway connection in the /// specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update virtual network gateway /// connection operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<VirtualNetworkGatewayConnection>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, VirtualNetworkGatewayConnection parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified virtual network Gateway connection. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The name of the virtual network gateway connection. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The Put VirtualNetworkGatewayConnectionSharedKey operation sets the /// virtual network gateway connection shared key for passed virtual /// network gateway connection in the specified resource group through /// Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection name. /// </param> /// <param name='parameters'> /// Parameters supplied to the Begin Set Virtual Network Gateway /// connection Shared key operation throughNetwork resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionSharedKey>> BeginSetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The VirtualNetworkGatewayConnectionResetSharedKey operation resets /// the virtual network gateway connection shared key for passed /// virtual network gateway connection in the specified resource group /// through Network resource provider. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='virtualNetworkGatewayConnectionName'> /// The virtual network gateway connection reset shared key Name. /// </param> /// <param name='parameters'> /// Parameters supplied to the begin reset virtual network gateway /// connection shared key operation through network resource provider. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ConnectionResetSharedKey>> BeginResetSharedKeyWithHttpMessagesAsync(string resourceGroupName, string virtualNetworkGatewayConnectionName, ConnectionResetSharedKey parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// The List VirtualNetworkGatewayConnections operation retrieves all /// the virtual network gateways connections created. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<VirtualNetworkGatewayConnection>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Tests.Common; using System.Threading; namespace OpenSim.Region.Framework.Scenes.Tests { [TestFixture] public class ScenePresenceSitTests : OpenSimTestCase { private TestScene m_scene; private ScenePresence m_sp; [SetUp] public void Init() { m_scene = new SceneHelpers().SetupScene(); m_sp = SceneHelpers.AddScenePresence(m_scene, TestHelpers.ParseTail(0x1)); } [Test] public void TestSitOutsideRangeNoTarget() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // More than 10 meters away from 0, 0, 0 (default part position) Vector3 startPos = new Vector3(10.1f, 0, 0); m_sp.AbsolutePosition = startPos; SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart; m_sp.HandleAgentRequestSit(m_sp.ControllingClient, m_sp.UUID, part.UUID, Vector3.Zero); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(0)); Assert.That(part.GetSittingAvatars(), Is.Null); Assert.That(m_sp.ParentID, Is.EqualTo(0)); Assert.AreEqual(startPos, m_sp.AbsolutePosition); } [Test] public void TestSitWithinRangeNoTarget() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // Less than 10 meters away from 0, 0, 0 (default part position) Vector3 startPos = new Vector3(9.9f, 0, 0); m_sp.AbsolutePosition = startPos; SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart; // We need to preserve this here because phys actor is removed by the sit. Vector3 spPhysActorSize = m_sp.PhysicsActor.Size; m_sp.HandleAgentRequestSit(m_sp.ControllingClient, m_sp.UUID, part.UUID, Vector3.Zero); Assert.That(m_sp.PhysicsActor, Is.Null); Assert.That( m_sp.AbsolutePosition, Is.EqualTo(part.AbsolutePosition + new Vector3(0, 0, spPhysActorSize.Z / 2))); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(1)); HashSet<ScenePresence> sittingAvatars = part.GetSittingAvatars(); Assert.That(sittingAvatars.Count, Is.EqualTo(1)); Assert.That(sittingAvatars.Contains(m_sp)); Assert.That(m_sp.ParentID, Is.EqualTo(part.LocalId)); } [Test] public void TestSitAndStandWithNoSitTarget() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // Make sure we're within range to sit Vector3 startPos = new Vector3(1, 1, 1); m_sp.AbsolutePosition = startPos; SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart; // We need to preserve this here because phys actor is removed by the sit. Vector3 spPhysActorSize = m_sp.PhysicsActor.Size; m_sp.HandleAgentRequestSit(m_sp.ControllingClient, m_sp.UUID, part.UUID, Vector3.Zero); Assert.That( m_sp.AbsolutePosition, Is.EqualTo(part.AbsolutePosition + new Vector3(0, 0, spPhysActorSize.Z / 2))); m_sp.StandUp(); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(0)); Assert.That(part.GetSittingAvatars(), Is.Null); Assert.That(m_sp.ParentID, Is.EqualTo(0)); Assert.That(m_sp.PhysicsActor, Is.Not.Null); } [Test] public void TestSitAndStandWithNoSitTargetChildPrim() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // Make sure we're within range to sit Vector3 startPos = new Vector3(1, 1, 1); m_sp.AbsolutePosition = startPos; SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene, 2, m_sp.UUID, "part", 0x10).Parts[1]; part.OffsetPosition = new Vector3(2, 3, 4); // We need to preserve this here because phys actor is removed by the sit. Vector3 spPhysActorSize = m_sp.PhysicsActor.Size; m_sp.HandleAgentRequestSit(m_sp.ControllingClient, m_sp.UUID, part.UUID, Vector3.Zero); Assert.That( m_sp.AbsolutePosition, Is.EqualTo(part.AbsolutePosition + new Vector3(0, 0, spPhysActorSize.Z / 2))); m_sp.StandUp(); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(0)); Assert.That(part.GetSittingAvatars(), Is.Null); Assert.That(m_sp.ParentID, Is.EqualTo(0)); Assert.That(m_sp.PhysicsActor, Is.Not.Null); } [Test] public void TestSitAndStandWithSitTarget() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // If a prim has a sit target then we can sit from any distance away Vector3 startPos = new Vector3(128, 128, 30); m_sp.AbsolutePosition = startPos; SceneObjectPart part = SceneHelpers.AddSceneObject(m_scene).RootPart; part.SitTargetPosition = new Vector3(0, 0, 1); m_sp.HandleAgentRequestSit(m_sp.ControllingClient, m_sp.UUID, part.UUID, Vector3.Zero); Assert.That(part.SitTargetAvatar, Is.EqualTo(m_sp.UUID)); Assert.That(m_sp.ParentID, Is.EqualTo(part.LocalId)); // This section is copied from ScenePresence.HandleAgentSit(). Correctness is not guaranteed. double x, y, z, m1, m2; Quaternion r = part.SitTargetOrientation;; m1 = r.X * r.X + r.Y * r.Y; m2 = r.Z * r.Z + r.W * r.W; // Rotate the vector <0, 0, 1> x = 2 * (r.X * r.Z + r.Y * r.W); y = 2 * (-r.X * r.W + r.Y * r.Z); z = m2 - m1; // Set m to be the square of the norm of r. double m = m1 + m2; // This constant is emperically determined to be what is used in SL. // See also http://opensimulator.org/mantis/view.php?id=7096 double offset = 0.05; Vector3 up = new Vector3((float)x, (float)y, (float)z); Vector3 sitOffset = up * (float)offset; // End of copied section. Assert.That( m_sp.AbsolutePosition, Is.EqualTo(part.AbsolutePosition + part.SitTargetPosition - sitOffset + ScenePresence.SIT_TARGET_ADJUSTMENT)); Assert.That(m_sp.PhysicsActor, Is.Null); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(1)); HashSet<ScenePresence> sittingAvatars = part.GetSittingAvatars(); Assert.That(sittingAvatars.Count, Is.EqualTo(1)); Assert.That(sittingAvatars.Contains(m_sp)); m_sp.StandUp(); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(m_sp.ParentID, Is.EqualTo(0)); Assert.That(m_sp.PhysicsActor, Is.Not.Null); Assert.That(part.SitTargetAvatar, Is.EqualTo(UUID.Zero)); Assert.That(part.GetSittingAvatarsCount(), Is.EqualTo(0)); Assert.That(part.GetSittingAvatars(), Is.Null); } [Test] public void TestSitAndStandOnGround() { TestHelpers.InMethod(); // log4net.Config.XmlConfigurator.Configure(); // If a prim has a sit target then we can sit from any distance away // Vector3 startPos = new Vector3(128, 128, 30); // sp.AbsolutePosition = startPos; m_sp.HandleAgentSitOnGround(); Assert.That(m_sp.SitGround, Is.True); Assert.That(m_sp.PhysicsActor, Is.Null); m_sp.StandUp(); Assert.That(m_sp.SitGround, Is.False); Assert.That(m_sp.PhysicsActor, Is.Not.Null); } } }
namespace Cinotam.AbpModuleZero.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class Upgraded_To_V0_9 : DbMigration { public override void Up() { DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); AlterTableAnnotations( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_PermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLogin_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserRole_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Setting_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AlterTableAnnotations( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", new AnnotationValues(oldValue: null, newValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition") }, }); AddColumn("dbo.AbpPermissions", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserLogins", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserRoles", "TenantId", c => c.Int()); AddColumn("dbo.AbpUserNotifications", "TenantId", c => c.Int()); AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 255)); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); //Update current AbpUserRoles.TenantId values Sql(@"UPDATE AbpUserRoles SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserRoles.UserId = AbpUsers.Id"); //Update current AbpUserLogins.TenantId values Sql(@"UPDATE AbpUserLogins SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserLogins.UserId = AbpUsers.Id"); //Update current AbpPermissions.TenantId values Sql(@"UPDATE AbpPermissions SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpPermissions.UserId = AbpUsers.Id"); Sql(@"UPDATE AbpPermissions SET TenantId = AbpRoles.TenantId FROM AbpRoles WHERE AbpPermissions.RoleId = AbpRoles.Id"); //Update current AbpUserNotifications.TenantId values Sql(@"UPDATE AbpUserNotifications SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpUserNotifications.UserId = AbpUsers.Id"); //Update current AbpSettings.TenantId values Sql(@"UPDATE AbpSettings SET TenantId = AbpUsers.TenantId FROM AbpUsers WHERE AbpSettings.UserId = AbpUsers.Id"); } public override void Down() { DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); AlterColumn("dbo.AbpUserLoginAttempts", "UserNameOrEmailAddress", c => c.String(maxLength: 256)); DropColumn("dbo.AbpUserNotifications", "TenantId"); DropColumn("dbo.AbpUserRoles", "TenantId"); DropColumn("dbo.AbpUserLogins", "TenantId"); DropColumn("dbo.AbpPermissions", "TenantId"); AlterTableAnnotations( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_Setting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserRole_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_UserLogin_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_PermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); AlterTableAnnotations( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, AnnotationValues> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", new AnnotationValues(oldValue: "EntityFramework.DynamicFilters.DynamicFilterDefinition", newValue: null) }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); CreateIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); AddForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants", "Id"); AddForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants", "Id"); AddForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants", "Id"); } } }
// Copyright 2018 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. using Firebase.Firestore.Internal; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using BclType = System.Type; namespace Firebase.Firestore.Converters { internal sealed class AttributedTypeConverter : MapConverterBase { // Note: the use of a dictionary for writable properties and a list for readable ones is purely // driven by how we use this. If we ever want a dictionary for readable properties, that's easy to do. private readonly Dictionary<string, AttributedProperty> _writableProperties; private readonly List<AttributedProperty> _readableProperties; private readonly Func<object> _createInstance; private readonly FirestoreDataAttribute _attribute; private AttributedTypeConverter(BclType targetType, FirestoreDataAttribute attribute) : base(targetType) { _attribute = attribute; // Check for user bugs in terms of attribute specifications. Preconditions.CheckState(Enum.IsDefined(typeof(UnknownPropertyHandling), _attribute.UnknownPropertyHandling), "Type {0} has invalid {1} value", targetType.FullName, nameof(FirestoreDataAttribute.UnknownPropertyHandling)); _createInstance = CreateObjectCreator(targetType); List<AttributedProperty> readableProperties = new List<AttributedProperty>(); Dictionary<string, AttributedProperty> writableProperties = new Dictionary<string, AttributedProperty>(); // We look for static properties specifically to find problems. We'll never use static properties. foreach (var property in targetType.GetProperties(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) { var propertyAttribute = Attribute.GetCustomAttribute(property, typeof(FirestorePropertyAttribute), inherit: true) as FirestorePropertyAttribute; if (propertyAttribute == null) { continue; } var attributedProperty = new AttributedProperty(property, propertyAttribute); string firestoreName = attributedProperty.FirestoreName; if (attributedProperty.IsNullableValue) { throw new NotSupportedException( String.Format("{0}.{1} is Nullable value type, which we do not support now due to a Unity limitation. " + "Try using a reference type instead.", targetType.FullName, property.Name)); } // Note that we check readable and writable properties separately. We could theoretically have // two separate properties, one read-only and one write-only, with the same name in Firestore. if (attributedProperty.CanRead) { // This is O(N), but done once per type so should be okay. Preconditions.CheckState(!readableProperties.Any(p => p.FirestoreName == firestoreName), "Type {0} contains multiple readable properties with name {1}", targetType.FullName, firestoreName); readableProperties.Add(attributedProperty); } if (attributedProperty.CanWrite) { Preconditions.CheckState(!writableProperties.ContainsKey(firestoreName), "Type {0} contains multiple writable properties with name {1}", targetType.FullName, firestoreName); writableProperties[firestoreName] = attributedProperty; } } _readableProperties = readableProperties; _writableProperties = writableProperties; } // Only used in the constructor, but extracted for readability. private static Func<object> CreateObjectCreator(BclType type) { if (type.IsValueType) { return () => Activator.CreateInstance(type); } else { // TODO: Consider using a compiled expression tree for this. var ctor = type .GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance) .SingleOrDefault(c => c.GetParameters().Length == 0); Preconditions.CheckState(ctor != null, "Type {0} has no parameterless constructor", type.FullName); return () => { try { return ctor.Invoke(parameters: null); } catch (TargetInvocationException e) { if (e.InnerException != null) { throw e.InnerException; } else { throw; } } }; } } /// <summary> /// Factory method to construct a converter for an attributed type. /// </summary> internal static IFirestoreInternalConverter ForType(BclType targetType) { var attribute = Attribute.GetCustomAttribute(targetType, typeof(FirestoreDataAttribute), inherit: false) as FirestoreDataAttribute; // This would be an internal library bug. We shouldn't be calling it in this case. Preconditions.CheckState(attribute != null, "Type {0} is not decorated with {1}.", targetType.FullName, nameof(FirestoreDataAttribute)); return attribute.ConverterType == null ? new AttributedTypeConverter(targetType, attribute) : CustomConverter.ForConverterType(attribute.ConverterType, targetType); } public // TODO(b/141568173): Significant newline. override object DeserializeMap(DeserializationContext context, FieldValueProxy mapValue) { Preconditions.CheckState(mapValue.type() == FieldValueProxy.Type.Map, "Expected to receive a map FieldValue"); object ret = _createInstance(); using (var map = FirestoreCpp.ConvertFieldValueToMap(mapValue)) { var iter = map.Iterator(); while (iter.HasMore()) { var key = iter.UnsafeKeyView(); FieldValueProxy value = iter.UnsafeValueView(); iter.Advance(); if (_writableProperties.TryGetValue(key, out var property)) { property.SetValue(context, value, ret); } else { switch (_attribute.UnknownPropertyHandling) { case UnknownPropertyHandling.Ignore: break; case UnknownPropertyHandling.Warn: Firebase.LogUtil.LogMessage(LogLevel.Warning, String.Format( "No writable property for Firestore field {0} in type {1}", key, TargetType.FullName)); break; case UnknownPropertyHandling.Throw: throw new ArgumentException(String.Format("No writable property for Firestore field {key} in type {0}", TargetType.FullName)); } } } } AttributedIdAssigner.MaybeAssignId(ret, context.DocumentReference); // NOTE: We don't support ReadTime, UpdateTime, etc. so we don't have the // AttributedTimestampAssigner that google-cloud-dotnet does. return ret; } public override void SerializeMap(SerializationContext context, object value, IDictionary<string, FieldValueProxy> map) { foreach (var property in _readableProperties) { map[property.FirestoreName] = property.GetSerializedValue(context, value); } } private sealed class AttributedProperty { private readonly PropertyInfo _propertyInfo; private FieldValueProxy _sentinelValue; private readonly IFirestoreInternalConverter _converter; /// <summary> /// The name to use in Firestore serialization/deserialization. Defaults to the property /// name, but may be specified in <see cref="FirestorePropertyAttribute"/>. /// </summary> internal readonly string FirestoreName; internal bool CanRead => _propertyInfo.CanRead; internal bool CanWrite => _propertyInfo.CanWrite; internal bool IsNullableValue => _propertyInfo.PropertyType.IsGenericType && _propertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>); internal AttributedProperty(PropertyInfo property, FirestorePropertyAttribute attribute) { _propertyInfo = property; FirestoreName = attribute.Name ?? property.Name; if (property.IsDefined(typeof(ServerTimestampAttribute), inherit: true)) { _sentinelValue = FieldValueProxy.ServerTimestamp(); } if (attribute.ConverterType != null) { _converter = CustomConverter.ForConverterType(attribute.ConverterType, property.PropertyType); } string typeName = property.DeclaringType.FullName; Preconditions.CheckState(property.GetIndexParameters().Length == 0, "{0}.{1} is an indexer, and should not be decorated with {2}.", typeName, property.Name, nameof(FirestorePropertyAttribute)); // Annoyingly, we can't easily check whether the property is static - we have to check the individual methods. var getMethod = property.GetGetMethod(nonPublic: true); var setMethod = property.GetSetMethod(nonPublic: true); Preconditions.CheckState(getMethod == null || !getMethod.IsStatic, "{0}.{1} is static, and should not be decorated with {2}.", typeName, property.Name, nameof(FirestorePropertyAttribute)); Preconditions.CheckState(setMethod == null || !setMethod.IsStatic, "{0}.{1} is static, and should not be decorated with {2}.", typeName, property.Name, nameof(FirestorePropertyAttribute)); // NOTE: We don't support ValueTupleConverter even though google-cloud-dotnet // does since it depends on .Net 4.7. } // TODO: Consider creating delegates for the property get/set methods. // Note: these methods have to handle null values when there's a custom converter involved, just like ValueSerializer/ValueDeserializer do. internal FieldValueProxy GetSerializedValue(SerializationContext context, object obj) { if (_sentinelValue != null) { return _sentinelValue; } object propertyValue = _propertyInfo.GetValue(obj, index: null); return _converter == null ? ValueSerializer.Serialize(context, propertyValue) : propertyValue == null ? FieldValueProxy.Null() : _converter.Serialize(context, propertyValue); } internal void SetValue(DeserializationContext context, FieldValueProxy value, object target) { object converted = _converter == null ? ValueDeserializer.Deserialize(context, value, _propertyInfo.PropertyType) : value.is_null() ? null : _converter.DeserializeValue(context, value); _propertyInfo.SetValue(target, converted, index: null); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics.Arm\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.Arm; namespace JIT.HardwareIntrinsics.Arm { public static partial class Program { private static void AddScalarSingle() { var test = new SimpleBinaryOpTest__AddScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); } // Validates passing a static member works test.RunClsVarScenario(); if (AdvSimd.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (AdvSimd.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (AdvSimd.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (AdvSimd.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector64<Single> _fld1; public Vector64<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddScalarSingle testClass) { var result = AdvSimd.AddScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddScalarSingle testClass) { fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 8; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector64<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector64<Single> _clsVar1; private static Vector64<Single> _clsVar2; private Vector64<Single> _fld1; private Vector64<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); } public SimpleBinaryOpTest__AddScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector64<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector64<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => AdvSimd.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = AdvSimd.AddScalar( Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.AddScalar), new Type[] { typeof(Vector64<Single>), typeof(Vector64<Single>) }) .Invoke(null, new object[] { AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)), AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector64<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = AdvSimd.AddScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector64<Single>* pClsVar1 = &_clsVar1) fixed (Vector64<Single>* pClsVar2 = &_clsVar2) { var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(pClsVar1)), AdvSimd.LoadVector64((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector64<Single>>(_dataTable.inArray2Ptr); var result = AdvSimd.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray1Ptr)); var op2 = AdvSimd.LoadVector64((Single*)(_dataTable.inArray2Ptr)); var result = AdvSimd.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddScalarSingle(); var result = AdvSimd.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddScalarSingle(); fixed (Vector64<Single>* pFld1 = &test._fld1) fixed (Vector64<Single>* pFld2 = &test._fld2) { var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = AdvSimd.AddScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector64<Single>* pFld1 = &_fld1) fixed (Vector64<Single>* pFld2 = &_fld2) { var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(pFld1)), AdvSimd.LoadVector64((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = AdvSimd.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = AdvSimd.AddScalar( AdvSimd.LoadVector64((Single*)(&test._fld1)), AdvSimd.LoadVector64((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector64<Single> op1, Vector64<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector64<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector64<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != 0) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.AddScalar)}<Single>(Vector64<Single>, Vector64<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Xml; using System.Xml.XPath; namespace MS.Internal.Xml.XPath { internal sealed class XPathScanner { private readonly string _xpathExpr; private int _xpathExprIndex; private LexKind _kind; private char _currentChar; private string _name; private string _prefix; private string _stringValue; private double _numberValue = double.NaN; private bool _canBeFunction; private XmlCharType _xmlCharType = XmlCharType.Instance; public XPathScanner(string xpathExpr) { if (xpathExpr == null) { throw XPathException.Create(SR.Xp_ExprExpected, string.Empty); } _xpathExpr = xpathExpr; NextChar(); NextLex(); } public string SourceText { get { return _xpathExpr; } } private char CurrentChar { get { return _currentChar; } } private bool NextChar() { Debug.Assert(0 <= _xpathExprIndex && _xpathExprIndex <= _xpathExpr.Length); if (_xpathExprIndex < _xpathExpr.Length) { _currentChar = _xpathExpr[_xpathExprIndex++]; return true; } else { _currentChar = '\0'; return false; } } #if XML10_FIFTH_EDITION private char PeekNextChar() { Debug.Assert(0 <= xpathExprIndex && xpathExprIndex <= xpathExpr.Length); if (xpathExprIndex < xpathExpr.Length) { return xpathExpr[xpathExprIndex]; } else { Debug.Assert(xpathExprIndex == xpathExpr.Length); return '\0'; } } #endif public LexKind Kind { get { return _kind; } } public string Name { get { Debug.Assert(_kind == LexKind.Name || _kind == LexKind.Axe); Debug.Assert(_name != null); return _name; } } public string Prefix { get { Debug.Assert(_kind == LexKind.Name); Debug.Assert(_prefix != null); return _prefix; } } public string StringValue { get { Debug.Assert(_kind == LexKind.String); Debug.Assert(_stringValue != null); return _stringValue; } } public double NumberValue { get { Debug.Assert(_kind == LexKind.Number); Debug.Assert(!double.IsNaN(_numberValue)); return _numberValue; } } // To parse PathExpr we need a way to distinct name from function. // This distinction can't be done without context: "or (1 != 0)" this is a function or 'or' in OrExp public bool CanBeFunction { get { Debug.Assert(_kind == LexKind.Name); return _canBeFunction; } } private void SkipSpace() { while (_xmlCharType.IsWhiteSpace(this.CurrentChar) && NextChar()) ; } public bool NextLex() { SkipSpace(); switch (this.CurrentChar) { case '\0': _kind = LexKind.Eof; return false; case ',': case '@': case '(': case ')': case '|': case '*': case '[': case ']': case '+': case '-': case '=': case '#': case '$': _kind = (LexKind)Convert.ToInt32(this.CurrentChar, CultureInfo.InvariantCulture); NextChar(); break; case '<': _kind = LexKind.Lt; NextChar(); if (this.CurrentChar == '=') { _kind = LexKind.Le; NextChar(); } break; case '>': _kind = LexKind.Gt; NextChar(); if (this.CurrentChar == '=') { _kind = LexKind.Ge; NextChar(); } break; case '!': _kind = LexKind.Bang; NextChar(); if (this.CurrentChar == '=') { _kind = LexKind.Ne; NextChar(); } break; case '.': _kind = LexKind.Dot; NextChar(); if (this.CurrentChar == '.') { _kind = LexKind.DotDot; NextChar(); } else if (XmlCharType.IsDigit(this.CurrentChar)) { _kind = LexKind.Number; _numberValue = ScanFraction(); } break; case '/': _kind = LexKind.Slash; NextChar(); if (this.CurrentChar == '/') { _kind = LexKind.SlashSlash; NextChar(); } break; case '"': case '\'': _kind = LexKind.String; _stringValue = ScanString(); break; default: if (XmlCharType.IsDigit(this.CurrentChar)) { _kind = LexKind.Number; _numberValue = ScanNumber(); } else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar) #endif ) { _kind = LexKind.Name; _name = ScanName(); _prefix = string.Empty; // "foo:bar" is one lexeme not three because it doesn't allow spaces in between // We should distinct it from "foo::" and need process "foo ::" as well if (this.CurrentChar == ':') { NextChar(); // can be "foo:bar" or "foo::" if (this.CurrentChar == ':') { // "foo::" NextChar(); _kind = LexKind.Axe; } else { // "foo:*", "foo:bar" or "foo: " _prefix = _name; if (this.CurrentChar == '*') { NextChar(); _name = "*"; } else if (_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar) #endif ) { _name = ScanName(); } else { throw XPathException.Create(SR.Xp_InvalidName, SourceText); } } } else { SkipSpace(); if (this.CurrentChar == ':') { NextChar(); // it can be "foo ::" or just "foo :" if (this.CurrentChar == ':') { NextChar(); _kind = LexKind.Axe; } else { throw XPathException.Create(SR.Xp_InvalidName, SourceText); } } } SkipSpace(); _canBeFunction = (this.CurrentChar == '('); } else { throw XPathException.Create(SR.Xp_InvalidToken, SourceText); } break; } return true; } private double ScanNumber() { Debug.Assert(this.CurrentChar == '.' || XmlCharType.IsDigit(this.CurrentChar)); int start = _xpathExprIndex - 1; int len = 0; while (XmlCharType.IsDigit(this.CurrentChar)) { NextChar(); len++; } if (this.CurrentChar == '.') { NextChar(); len++; while (XmlCharType.IsDigit(this.CurrentChar)) { NextChar(); len++; } } return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len)); } private double ScanFraction() { Debug.Assert(XmlCharType.IsDigit(this.CurrentChar)); int start = _xpathExprIndex - 2; Debug.Assert(0 <= start && _xpathExpr[start] == '.'); int len = 1; // '.' while (XmlCharType.IsDigit(this.CurrentChar)) { NextChar(); len++; } return XmlConvert.ToXPathDouble(_xpathExpr.Substring(start, len)); } private string ScanString() { char endChar = this.CurrentChar; NextChar(); int start = _xpathExprIndex - 1; int len = 0; while (this.CurrentChar != endChar) { if (!NextChar()) { throw XPathException.Create(SR.Xp_UnclosedString); } len++; } Debug.Assert(this.CurrentChar == endChar); NextChar(); return _xpathExpr.Substring(start, len); } private string ScanName() { Debug.Assert(_xmlCharType.IsStartNCNameSingleChar(this.CurrentChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(this.CurerntChar) #endif ); int start = _xpathExprIndex - 1; int len = 0; while (true) { if (_xmlCharType.IsNCNameSingleChar(this.CurrentChar)) { NextChar(); len++; } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(this.PeekNextChar(), this.CurerntChar)) { NextChar(); NextChar(); len += 2; } #endif else { break; } } return _xpathExpr.Substring(start, len); } public enum LexKind { Comma = ',', Slash = '/', At = '@', Dot = '.', LParens = '(', RParens = ')', LBracket = '[', RBracket = ']', Star = '*', Plus = '+', Minus = '-', Eq = '=', Lt = '<', Gt = '>', Bang = '!', Dollar = '$', Apos = '\'', Quote = '"', Union = '|', Ne = 'N', // != Le = 'L', // <= Ge = 'G', // >= And = 'A', // && Or = 'O', // || DotDot = 'D', // .. SlashSlash = 'S', // // Name = 'n', // XML _Name String = 's', // Quoted string constant Number = 'd', // _Number constant Axe = 'a', // Axe (like child::) Eof = 'E', }; } }
using System; using System.Collections.Generic; using System.Text; namespace gView.Framework.Data { public class SimpleRowCursor : IRowCursor { private List<IRow> _rows; private int _pos = 0; public SimpleRowCursor(List<IRow> rows) { _rows = rows; } #region IRowCursor Member public IRow NextRow { get { if (_rows == null || _pos >= _rows.Count) return null; return _rows[_pos++]; } } #endregion #region IDisposable Member public void Dispose() { } #endregion } public class SimpleFeatureCursor : IFeatureCursor { private List<IFeature> _features; private int _pos = 0; public SimpleFeatureCursor(List<IFeature> features) { _features = features; } #region IFeatureCursor Member public IFeature NextFeature { get { if (_features == null || _pos >= _features.Count) return null; return _features[_pos++]; } } #endregion #region IDisposable Member public void Dispose() { } #endregion } public class SimpleRasterlayerCursor : IRasterLayerCursor { private List<IRasterLayer> _layers; private int _pos = 0; public SimpleRasterlayerCursor(List<IRasterLayer> layers) { _layers = layers; } #region IRasterLayerCursor Member public IRasterLayer NextRasterLayer { get { if (_layers == null || _pos >= _layers.Count) return null; return _layers[_pos++]; } } #endregion #region IDisposable Member public void Dispose() { } #endregion } public class CursorCollection<T> : IFeatureCursor { private Dictionary<T, IFeatureClass> _fcs; private Dictionary<T, QueryFilter> _filters; private Dictionary<T, Dictionary<int, List<FieldValue>>> _additionalFields; private IFeatureCursor _cursor = null; private int index = 0; private List<T> _keys = new List<T>(); public CursorCollection(Dictionary<T, IFeatureClass> fcs, Dictionary<T, QueryFilter> filters, Dictionary<T, Dictionary<int, List<FieldValue>>> additionalFields = null) { _fcs = fcs; _filters = filters; _additionalFields = additionalFields; if (_fcs != null && _filters != null) { foreach (T key in _fcs.Keys) { if (_filters.ContainsKey(key)) _keys.Add(key); } } } #region IFeatureCursor Member public IFeature NextFeature { get { try { if (_cursor == null) { if (index >= _keys.Count) return null; T key = _keys[index++]; _cursor = _fcs[key].GetFeatures(_filters[key]); if (_cursor == null) return NextFeature; } IFeature feature = _cursor.NextFeature; if (feature == null) { _cursor.Dispose(); _cursor = null; return NextFeature; } if (_fcs.ContainsKey(_keys[index-1])) { var fc = _fcs[_keys[index-1]]; if (fc != null) feature.Fields.Add(new FieldValue("_classname", fc.Name)); } if (_additionalFields != null) { var fcDictionary = _additionalFields[_keys[index-1]]; if (fcDictionary != null && fcDictionary.ContainsKey(feature.OID) && fcDictionary[feature.OID] != null) { var fields = fcDictionary[feature.OID]; foreach (var fieldValue in fields) { feature.Fields.Add(fieldValue); } } } return feature; } catch { return null; } } } #endregion #region IDisposable Member public void Dispose() { if (_cursor != null) { _cursor.Dispose(); _cursor = null; } } #endregion } }
// -- FILE ------------------------------------------------------------------ // name : DateAdd.cs // project : Itenso Time Period // created : Jani Giannoudis - 2011.03.19 // language : C# 4.0 // environment: .NET 2.0 // copyright : (c) 2011-2012 by Itenso GmbH, Switzerland // -------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace Itenso.TimePeriod { // ------------------------------------------------------------------------ public class DateAdd { // ---------------------------------------------------------------------- public ITimePeriodCollection IncludePeriods { get { return includePeriods; } } // IncludePeriods // ---------------------------------------------------------------------- public ITimePeriodCollection ExcludePeriods { get { return excludePeriods; } } // ExcludePeriods // ---------------------------------------------------------------------- public virtual DateTime? Subtract( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next ) { if ( includePeriods.Count == 0 && excludePeriods.Count == 0 ) { return start.Subtract( offset ); } TimeSpan? remaining; return offset < TimeSpan.Zero ? CalculateEnd( start, offset.Negate(), SeekDirection.Forward, seekBoundaryMode, out remaining ) : CalculateEnd( start, offset, SeekDirection.Backward, seekBoundaryMode, out remaining ); } // Subtract // ---------------------------------------------------------------------- public virtual DateTime? Add( DateTime start, TimeSpan offset, SeekBoundaryMode seekBoundaryMode = SeekBoundaryMode.Next ) { if ( includePeriods.Count == 0 && excludePeriods.Count == 0 ) { return start.Add( offset ); } TimeSpan? remaining; return offset < TimeSpan.Zero ? CalculateEnd( start, offset.Negate(), SeekDirection.Backward, seekBoundaryMode, out remaining ) : CalculateEnd( start, offset, SeekDirection.Forward, seekBoundaryMode, out remaining ); } // Add // ---------------------------------------------------------------------- protected DateTime? CalculateEnd( DateTime start, TimeSpan offset, SeekDirection seekDirection, SeekBoundaryMode seekBoundaryMode, out TimeSpan? remaining ) { if ( offset < TimeSpan.Zero ) { throw new InvalidOperationException( "time span must be positive" ); } remaining = offset; // search periods TimePeriodCollection searchPeriods = new TimePeriodCollection( includePeriods ); // no search periods specified: search anytime if ( searchPeriods.Count == 0 ) { searchPeriods.Add( TimeRange.Anytime ); } // available periods ITimePeriodCollection availablePeriods = new TimePeriodCollection(); // no exclude periods specified: use all search periods if ( excludePeriods.Count == 0 ) { availablePeriods.AddAll( searchPeriods ); } else // remove exclude periods { TimeGapCalculator<TimeRange> gapCalculator = new TimeGapCalculator<TimeRange>(); foreach ( ITimePeriod searchPeriod in searchPeriods ) { // no overlaps: use the entire search range if ( !excludePeriods.HasOverlapPeriods( searchPeriod ) ) { availablePeriods.Add( searchPeriod ); } else // add gaps of search period using the exclude periods { availablePeriods.AddAll( gapCalculator.GetGaps( excludePeriods, searchPeriod ) ); } } } // no periods available if ( availablePeriods.Count == 0 ) { return null; } // combine the available periods, ensure no overlapping // used for FindNextPeriod/FindPreviousPeriod if ( availablePeriods.Count > 1 ) { TimePeriodCombiner<TimeRange> periodCombiner = new TimePeriodCombiner<TimeRange>(); availablePeriods = periodCombiner.CombinePeriods( availablePeriods ); } // find the starting search period ITimePeriod startPeriod = null; DateTime seekMoment = start; switch ( seekDirection ) { case SeekDirection.Forward: startPeriod = FindNextPeriod( start, availablePeriods, out seekMoment ); break; case SeekDirection.Backward: startPeriod = FindPreviousPeriod( start, availablePeriods, out seekMoment ); break; } // no starting period available if ( startPeriod == null ) { return null; } // no offset: use the search staring position // maybe moved to the next available search period if ( offset == TimeSpan.Zero ) { return seekMoment; } // setup destination search switch ( seekDirection ) { case SeekDirection.Forward: for ( int i = availablePeriods.IndexOf( startPeriod ); i < availablePeriods.Count; i++ ) { ITimePeriod gap = availablePeriods[ i ]; TimeSpan gapRemining = gap.End - seekMoment; bool isTargetPeriod = false; switch ( seekBoundaryMode ) { case SeekBoundaryMode.Fill: isTargetPeriod = gapRemining >= remaining; break; case SeekBoundaryMode.Next: isTargetPeriod = gapRemining > remaining; break; } if ( isTargetPeriod ) { DateTime end = seekMoment + remaining.Value; remaining = null; return end; } remaining = remaining - gapRemining; if ( i == availablePeriods.Count - 1 ) { return null; } seekMoment = availablePeriods[ i + 1 ].Start; // next period } break; case SeekDirection.Backward: for ( int i = availablePeriods.IndexOf( startPeriod ); i >= 0; i-- ) { ITimePeriod gap = availablePeriods[ i ]; TimeSpan gapRemining = seekMoment - gap.Start; bool isTargetPeriod = false; switch ( seekBoundaryMode ) { case SeekBoundaryMode.Fill: isTargetPeriod = gapRemining >= remaining; break; case SeekBoundaryMode.Next: isTargetPeriod = gapRemining > remaining; break; } if ( isTargetPeriod ) { DateTime end = seekMoment - remaining.Value; remaining = null; return end; } remaining = remaining - gapRemining; if ( i == 0 ) { return null; } seekMoment = availablePeriods[ i - 1 ].End; // previous period } break; } return null; } // CalculateEnd // ---------------------------------------------------------------------- // assumes no no overlapping periods in parameter periods private static ITimePeriod FindNextPeriod( DateTime start, IEnumerable<ITimePeriod> periods, out DateTime moment ) { ITimePeriod nearestPeriod = null; TimeSpan difference = TimeSpan.MaxValue; moment = start; foreach ( ITimePeriod period in periods ) { // inside period if ( period.HasInside( start ) ) { nearestPeriod = period; moment = start; break; } // period out of range if ( period.End < start ) { continue; } // not the nearest TimeSpan periodToMoment = period.Start - start; if ( periodToMoment >= difference ) { continue; } difference = periodToMoment; nearestPeriod = period; moment = nearestPeriod.Start; } return nearestPeriod; } // FindNextPeriod // ---------------------------------------------------------------------- // assumes no no overlapping periods in parameter periods private static ITimePeriod FindPreviousPeriod( DateTime start, IEnumerable<ITimePeriod> periods, out DateTime moment ) { ITimePeriod nearestPeriod = null; TimeSpan difference = TimeSpan.MaxValue; moment = start; foreach ( ITimePeriod period in periods ) { // inside period if ( period.HasInside( start ) ) { nearestPeriod = period; moment = start; break; } // period out of range if ( period.Start > start ) { continue; } // not the nearest TimeSpan periodToMoment = start - period.End; if ( periodToMoment >= difference ) { continue; } difference = periodToMoment; nearestPeriod = period; moment = nearestPeriod.End; } return nearestPeriod; } // FindPreviousPeriod // ---------------------------------------------------------------------- // members private readonly TimePeriodCollection includePeriods = new TimePeriodCollection(); private readonly TimePeriodCollection excludePeriods = new TimePeriodCollection(); } // class DateAdd } // namespace Itenso.TimePeriod // -- EOF -------------------------------------------------------------------
namespace AirTicketQuery.Modules.Code { using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Text; using System.Text.RegularExpressions; /// <summary> /// SQL VerifyType /// </summary> public enum VerifyTypeEnum { /// <summary> /// windows /// </summary> Windows = 0, /// <summary> /// Database /// </summary> Database = 1 } /// <summary> /// The Database Class /// </summary> public class DB : IDisposable { #region Field /// <summary> /// Transaction /// </summary> private SqlTransaction sqltrans; /// <summary> /// Transaction IsolationLevel /// </summary> private IsolationLevel isolationLevel; /// <summary> /// DBConnection /// </summary> private SqlConnection sqlConn; /// <summary> /// database connect string /// </summary> private string dbConnStr = string.Empty; /// <summary> /// keepConnectionOpen /// </summary> private bool keepConnectionOpen = false; private bool needLog = true; #endregion #region Construct /// <summary> /// New /// </summary> public DB() { this.isolationLevel = IsolationLevel.ReadCommitted; } /// <summary> /// New /// </summary> /// <param name="dbConnParam">Database connent Class</param> public DB(DBConnectParams dbConnParam) { this.dbConnStr = dbConnParam.ToString(); this.isolationLevel = IsolationLevel.ReadCommitted; } /// <summary> /// New /// </summary> /// <param name="dbConnstring">Database connent string</param> public DB(string dbConnstring) { this.dbConnStr = dbConnstring; this.isolationLevel = IsolationLevel.ReadCommitted; } #endregion #region Property /// <summary> /// IsInTransaction /// </summary> public bool IsInTransaction { get { return this.sqltrans == null ? false : true; } } /// <summary> /// Transaction IsolationLevel /// </summary> public IsolationLevel TransIsolationLevel { get { return this.isolationLevel; } set { this.isolationLevel = value; } } /// <summary> /// keepConnectionOpen /// </summary> public bool KeepConnectionOpen { get { return this.keepConnectionOpen; } set { this.keepConnectionOpen = value; if (this.keepConnectionOpen) { this.sqlConn = new SqlConnection(this.DBConnString); } } } public bool NeedLog { get { return this.needLog; } set { this.needLog = value; } } /// <summary> /// Property ConnectionString is used to get tmis's database connection string. /// <remarks>The database connection string.</remarks> /// </summary> private string DBConnString { get { if (string.IsNullOrEmpty(this.dbConnStr)) { this.dbConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; } return this.dbConnStr; } } #endregion #region Construct & Init /// <summary> /// Init the Command and Connection /// </summary> /// <param name="cmd">SqlCommand</param> /// <param name="conn">SqlConnection</param> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> private void Init(ref SqlCommand cmd, ref SqlConnection conn, string strSQL, SqlParameter[] parameterArray) { if (string.IsNullOrEmpty(strSQL) || strSQL.Length < 4) { throw new Exception("The SQL is Error!"); } if (!this.IsInTransaction && !this.keepConnectionOpen) { conn = new SqlConnection(this.DBConnString); cmd = new SqlCommand(strSQL, conn); conn.Open(); } else { if (this.sqlConn == null) throw new Exception("The SqlConnection is not init!"); cmd = new SqlCommand(strSQL, this.sqlConn); if (this.IsInTransaction) cmd.Transaction = this.sqltrans; if (this.sqlConn.State != ConnectionState.Open) this.sqlConn.Open(); } if (parameterArray != null) { SqlParameter[] clonedParameters = new SqlParameter[parameterArray.Length]; for (int i = 0; i < parameterArray.Length; i++) { clonedParameters[i] = (SqlParameter)((ICloneable)parameterArray[i]).Clone(); } cmd.Parameters.AddRange(clonedParameters); } cmd.CommandType = CommandType.Text; cmd.CommandTimeout = 6000; } /// <summary> /// Init the Command and Connection Use Store Procedure /// </summary> /// <param name="cmd">SqlCommand</param> /// <param name="conn">SqlConnection</param> /// <param name="strSPName">strSPName</param> /// <param name="parameterArray">parameterArray</param> private void InitSP(ref SqlCommand cmd, ref SqlConnection conn, string strSPName, SqlParameter[] parameterArray) { if (strSPName.Length == 0) { throw new Exception("The Store Procedure Name is not assign!"); } if (!this.IsInTransaction && !this.keepConnectionOpen) { conn = new SqlConnection(this.DBConnString); cmd = new SqlCommand(strSPName, conn); conn.Open(); } else { if (this.sqlConn == null) throw new Exception("The SqlConnection is not init!"); cmd = new SqlCommand(strSPName, this.sqlConn); if (this.IsInTransaction) cmd.Transaction = this.sqltrans; if (this.sqlConn.State != ConnectionState.Open) this.sqlConn.Open(); } cmd.CommandType = CommandType.StoredProcedure; if (parameterArray != null) { SqlParameter[] clonedParameters = new SqlParameter[parameterArray.Length]; for (int i = 0; i < parameterArray.Length; i++) { clonedParameters[i] = (SqlParameter)((ICloneable)parameterArray[i]).Clone(); } cmd.Parameters.AddRange(clonedParameters); } cmd.CommandTimeout = 6000; } public bool TestDBConnect(out string strErrMsg) { bool result = false; strErrMsg = string.Empty; try { SqlConnection conn = new SqlConnection(this.DBConnString); try { conn.Open(); result = true; } catch (System.ArgumentException ex) { Log.LogErr(ex); strErrMsg = "Login failed for user.\r\n" + ex.Message; return false; } catch (System.Data.SqlClient.SqlException sqlException) { Log.LogErr(sqlException); strErrMsg = "The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.\r\n\r\n" + sqlException.Message; return false; } catch (Exception ex) { strErrMsg = ex.Message; result = false; } finally { if (conn != null) { if (conn.State == ConnectionState.Open) conn.Close(); conn = null; } } } catch { result = false; } return result; } #endregion #region Transaction /// <summary> /// BeginTransaction /// </summary> public void BeginTransaction() { if (this.sqlConn == null) this.sqlConn = new SqlConnection(this.DBConnString); if (this.sqlConn.State != ConnectionState.Open) this.sqlConn.Open(); this.sqltrans = this.sqlConn.BeginTransaction(this.TransIsolationLevel); } /// <summary> /// BeginTransaction /// </summary> /// <param name="transisolationLevel">IsolationLevel</param> public void BeginTransaction(IsolationLevel transisolationLevel) { if (this.sqlConn == null) this.sqlConn = new SqlConnection(this.DBConnString); if (this.sqlConn.State != ConnectionState.Open) this.sqlConn.Open(); this.sqltrans = this.sqlConn.BeginTransaction(transisolationLevel); } /// <summary> /// CommitTransaction /// </summary> public void CommitTransaction() { this.CommitTransaction(true); } /// <summary> /// CommitTransaction /// </summary> /// <param name="closeConnection">closeConnection</param> public void CommitTransaction(bool closeConnection) { this.sqltrans.Commit(); this.DisposeTransaction(closeConnection); } /// <summary> /// AbortTransaction /// </summary> public void AbortTransaction() { if (this.IsInTransaction) { this.sqltrans.Rollback(); this.DisposeTransaction(true); } } /// <summary> /// AbortTransaction /// </summary> /// <param name="closeConnection">closeConnection</param> public void AbortTransaction(bool closeConnection) { if (this.IsInTransaction) { this.sqltrans.Rollback(); this.DisposeTransaction(closeConnection); } } /// <summary> /// DisposeTransaction /// </summary> /// <param name="closeConnection">CloseConnection</param> private void DisposeTransaction(bool closeConnection) { if (closeConnection && this.sqlConn != null) { this.sqlConn.Close(); this.sqlConn.Dispose(); this.sqlConn = null; } this.sqltrans.Dispose(); this.sqltrans = null; } #endregion #region GetDataTable /// <summary> /// GetDataTable /// </summary> /// <param name="strSQL">SqlText</param> /// <returns>DataTable</returns> public DataTable GetDataTable(string strSQL) { return this.GetDataTable(strSQL, null); } /// <summary> /// GetDataTable /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns>DataTable</returns> public DataTable GetDataTable(string strSQL, SqlParameter[] parameterArray) { return this.GetDataSet(strSQL, parameterArray).Tables[0]; } #endregion #region GetDataView /// <summary> /// GetDataView /// </summary> /// <param name="strSQL">SqlText</param> /// <returns>DataView</returns> public DataView GetDataView(string strSQL) { return this.GetDataView(strSQL, null); } /// <summary> /// GetDataView /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns>DataView</returns> public DataView GetDataView(string strSQL, SqlParameter[] parameterArray) { return this.GetDataTable(strSQL, parameterArray).DefaultView; } #endregion #region GetPageData /// <summary> /// GetPageData /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="pageIndex">pageIndex</param> /// <param name="pageSize">pageSize</param> /// <returns>DataTable</returns> public DataTable GetPageData(string strSQL, int pageIndex, int pageSize) { return this.GetPageData(strSQL, pageIndex, pageSize, null); } /// <summary> /// GetPageData /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="pageIndex">pageIndex</param> /// <param name="pageSize">pageSize</param> /// <param name="parameterArray">parameterArray</param> /// <returns>DataTable</returns> public DataTable GetPageData(string strSQL, int pageIndex, int pageSize, SqlParameter[] parameterArray) { int startNum = (pageIndex - 1) * pageSize; DataSet ds = new DataSet(); SqlDataAdapter da = null; SqlCommand cmd = null; SqlConnection conn = null; try { da = new SqlDataAdapter(); this.Init(ref cmd, ref conn, strSQL, parameterArray); da.SelectCommand = cmd; da.Fill(ds, startNum, pageSize, "tableTmp"); } catch (Exception e) { if (this.needLog) Log.LogErr(strSQL, e); throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); da.Dispose(); } return ds.Tables["tableTmp"]; } #endregion #region GetDataSet /// <summary> /// GetDataSet /// </summary> /// <param name="strSQL">SqlText</param> /// <returns>DataSet</returns> public DataSet GetDataSet(string strSQL) { return this.GetDataSet(strSQL, null); } /// <summary> /// GetDataSet /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns>DataSet</returns> public DataSet GetDataSet(string strSQL, SqlParameter[] parameterArray) { DataSet ds = new DataSet(); SqlDataAdapter da = null; SqlCommand cmd = null; SqlConnection conn = null; try { da = new SqlDataAdapter(); this.Init(ref cmd, ref conn, strSQL, parameterArray); da.SelectCommand = cmd; ((SqlDataAdapter)da).Fill(ds); } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSQL + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); ((IDisposable)da).Dispose(); } return ds; } #endregion #region GetDataReader /// <summary> /// GetDataReader /// </summary> /// <param name="strSQL">SqlText</param> /// <returns>IDataReader</returns> public SqlDataReader GetDataReader(string strSQL) { return this.GetDataReader(strSQL, null); } /// <summary> /// GetDataReader /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns>IDataReader</returns> public SqlDataReader GetDataReader(string strSQL, SqlParameter[] parameterArray) { SqlCommand cmd = null; SqlConnection conn = null; SqlDataReader reader; try { this.Init(ref cmd, ref conn, strSQL, parameterArray); reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); } catch (Exception e) { if (!this.IsInTransaction) { conn.Close(); conn.Dispose(); } if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSQL + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { cmd.Parameters.Clear(); cmd.Dispose(); } return reader; } #endregion #region ExecNonQuery /// <summary> /// ExecNonQuery /// </summary> /// <param name="strSQL">SqlText</param> /// <returns></returns> public int ExecNonQuery(string strSQL) { return this.ExecNonQuery(strSQL, null); } /// <summary> /// ExecNonQuery /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns></returns> public int ExecNonQuery(string strSQL, SqlParameter[] parameterArray) { int i = 0; SqlCommand cmd = null; SqlConnection conn = null; if (strSQL == string.Empty) { return i; } try { this.Init(ref cmd, ref conn, strSQL, parameterArray); i = cmd.ExecuteNonQuery(); } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSQL + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); } return i; } #endregion #region ExecScalar /// <summary> /// ExecScalar /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="nullValue">when result is null,return nullValue</param> /// <returns></returns> public object ExecScalar(string strSQL, string nullValue) { return this.ExecScalar(strSQL, null, nullValue); } /// <summary> /// ExecScalar /// </summary> /// <param name="strSQL">SqlText</param> /// <returns></returns> public object ExecScalar(string strSQL) { return this.ExecScalar(strSQL, null, null); } /// <summary> /// ExecScalar /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <returns></returns> public object ExecScalar(string strSQL, SqlParameter[] parameterArray) { return this.ExecScalar(strSQL, parameterArray, null); } /// <summary> /// ExecScalar /// </summary> /// <param name="strSQL">SqlText</param> /// <param name="parameterArray">parameterArray</param> /// <param name="nullValue">when result is null,return nullValue</param> /// <returns></returns> public object ExecScalar(string strSQL, SqlParameter[] parameterArray, object nullValue) { object obj; SqlCommand cmd = null; SqlConnection conn = null; try { this.Init(ref cmd, ref conn, strSQL, parameterArray); obj = cmd.ExecuteScalar(); if (obj == null || obj == DBNull.Value) obj = nullValue; } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSQL + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); } return obj; } #endregion #region Store Procedure /// <summary> /// ExecNonQuery with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <returns></returns> public int ExecNonQuerySP(string strSPName) { int retvalue; return this.ExecNonQuerySP(strSPName, out retvalue, null); } /// <summary> /// ExecNonQuery with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <param name="retvalue">SP Return Value</param> /// <returns></returns> public int ExecNonQuerySP(string strSPName, out int retvalue) { return this.ExecNonQuerySP(strSPName, out retvalue, null); } /// <summary> /// ExecNonQuery with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <param name="parameterArray">parameterArray</param> /// <returns></returns> public int ExecNonQuerySP(string strSPName, SqlParameter[] parameterArray) { int retvalue; return this.ExecNonQuerySP(strSPName, out retvalue, parameterArray); } /// <summary> /// ExecNonQuery with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <param name="retvalue">SP Return Value</param> /// <param name="parameterArray">parameterArray</param> /// <returns></returns> public int ExecNonQuerySP(string strSPName, out int retvalue, SqlParameter[] parameterArray) { int i = 0; retvalue = 0; SqlCommand cmd = null; SqlConnection conn = null; if (string.IsNullOrEmpty(strSPName)) { throw new Exception("The Store Procedure Name is not assign!"); } try { this.InitSP(ref cmd, ref conn, strSPName, parameterArray); cmd.Parameters.Add("@Ret", SqlDbType.Int); cmd.Parameters["@Ret"].Direction = ParameterDirection.ReturnValue; i = cmd.ExecuteNonQuery(); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Direction == ParameterDirection.Output || parameterArray[j].Direction == ParameterDirection.InputOutput) { parameterArray[j].Value = cmd.Parameters[parameterArray[j].ParameterName].Value; } } } retvalue = (int)cmd.Parameters["@Ret"].Value; } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSPName + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); } return i; } /// <summary> /// GetDataTable with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <returns></returns> public DataTable GetDataTableSP(string strSPName) { return this.GetDataTableSP(strSPName, null); } /// <summary> /// GetDataTable with SP /// </summary> /// <param name="strSPName">SP Name</param> /// <param name="parameterArray">parameterArray</param> /// <returns></returns> public DataTable GetDataTableSP(string strSPName, SqlParameter[] parameterArray) { DataTable dtResult = new DataTable(); SqlCommand cmd = null; SqlConnection conn = null; if (string.IsNullOrEmpty(strSPName)) { throw new Exception("The Store Procedure Name is not assign!"); } try { this.InitSP(ref cmd, ref conn, strSPName, parameterArray); // Define the data adapter and fill the dataset using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { da.Fill(dtResult); } } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(strSPName + ";\n"); if (parameterArray != null) { for (int j = 0; j < parameterArray.Length; j++) { if (parameterArray[j].Value != null) { sbparam.Append( parameterArray[j].ParameterName + "=" + parameterArray[j].Value.ToString() + ";"); } else { sbparam.Append(parameterArray[j].ParameterName + "=null;"); } } } Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); conn.Dispose(); } cmd.Parameters.Clear(); cmd.Dispose(); } return dtResult; } #endregion #region WriteDataToTempTable private void CreateTmpTable(DataTable dt) { string s = string.Empty; if (string.IsNullOrEmpty(dt.TableName)) dt.TableName = "#tempTable"; string coll = this.ExecScalar("SELECT SERVERPROPERTY('collation')").ToString(); foreach (DataColumn dc in dt.Columns) { s += ",[" + dc.ColumnName + "]"; string t = dc.DataType.BaseType.Name.ToLower(); if (t.IndexOf("int") > -1) { s += " int null"; } else if (t.IndexOf("double") > -1) { s += " double null"; } else if (t.IndexOf("float") > -1) { s += " float null"; } else if (t.IndexOf("date") > -1) { s += " datetime null"; } else { if (string.IsNullOrEmpty(coll)) { s += " varchar(50) null "; } else { s += " varchar(50) COLLATE " + coll + " null"; } } } string sql = string.Concat("create table #", dt.TableName.Replace("#", string.Empty), " (", s.Substring(1), ")"); this.ExecNonQuery(sql); } public void WriteData(DataTable dt, string tableName) { SqlConnection conn = null; try { try { if (!this.IsInTransaction && !this.keepConnectionOpen) { conn = new SqlConnection(this.DBConnString); conn.Open(); } else { conn = this.sqlConn; if (conn.State != ConnectionState.Open) conn.Open(); } if (string.IsNullOrEmpty(tableName)) { if (string.IsNullOrEmpty(dt.TableName)) dt.TableName = "#tempTable"; this.CreateTmpTable(dt); tableName = dt.TableName; } SqlBulkCopy sbc; if (!this.IsInTransaction) { sbc = new SqlBulkCopy(conn); } else { sbc = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, this.sqltrans); } sbc.DestinationTableName = tableName; // Set up the column mappings by name. foreach (DataColumn dcItem in dt.Columns) { SqlBulkCopyColumnMapping mapID = new SqlBulkCopyColumnMapping(dcItem.ColumnName, dcItem.ColumnName); sbc.ColumnMappings.Add(mapID); } sbc.WriteToServer(dt); sbc.Close(); } catch (Exception e) { if (this.needLog) Log.LogErr(e); throw; } } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { conn.Close(); } } } #endregion #region UpdateDataset /// <summary> /// update table by DataSet /// </summary> /// <param name="dataSet">DataSet</param> /// <param name="tableName">tableName</param> public int UpdateDataset(DataSet dataSet, string tableName) { return this.UpdateDataset(dataSet, tableName, string.Empty, string.Empty, null, null); } /// <summary> /// update table by DataSet /// </summary> /// <param name="dataSet">DataSet</param> /// <param name="tableName">tableName</param> /// <param name="deleteCommandText">deleteCommandText</param> /// <param name="updateCommandText">updateCommandText</param> /// <param name="needUpdateColName">needUpdateColName,use for updateCommand and deleteCommandText</param> /// <param name="prikeyColName">prikeyColName,use for updateCommand and deleteCommandText</param> public int UpdateDataset(DataSet dataSet, string tableName, string deleteCommandText, string updateCommandText, List<string> needUpdateColName, List<string> prikeyColName) { int result = 0; string sSql = "Select * from " + tableName; if (!this.IsInTransaction && !this.keepConnectionOpen && this.sqlConn == null) { this.sqlConn = new SqlConnection(this.DBConnString); } if (this.sqlConn.State == ConnectionState.Closed) this.sqlConn.Open(); try { // Create a SqlDataAdapter, and dispose of it after we are done using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sSql, this.sqlConn)) { dataAdapter.UpdateBatchSize = 10; if (this.IsInTransaction) { dataAdapter.SelectCommand.Transaction = this.sqltrans; } SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); commandBuilder.QuotePrefix = "["; commandBuilder.QuoteSuffix = "]"; dataAdapter.InsertCommand = commandBuilder.GetInsertCommand(); if (string.IsNullOrEmpty(deleteCommandText)) { dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand(); } else { dataAdapter.DeleteCommand = new SqlCommand(deleteCommandText, this.sqlConn); int priKeyCount = 0; foreach (SqlParameter mParam in commandBuilder.GetDeleteCommand().Parameters) { if (priKeyCount < prikeyColName.Count && prikeyColName.Contains(mParam.SourceColumn)) { dataAdapter.DeleteCommand.Parameters.Add(string.Format("@{0}", mParam.SourceColumn), mParam.SqlDbType, mParam.Size, mParam.SourceColumn); priKeyCount++; } if (priKeyCount == prikeyColName.Count) { break; } } dataAdapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None; } if (string.IsNullOrEmpty(updateCommandText)) { dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand(); } else { dataAdapter.UpdateCommand = new SqlCommand(updateCommandText, this.sqlConn); int priKeyCount = 0; int updateColCount = 0; foreach (SqlParameter mParam in commandBuilder.GetUpdateCommand().Parameters) { if (priKeyCount < prikeyColName.Count && prikeyColName.Contains(mParam.SourceColumn.ToUpper())) { dataAdapter.UpdateCommand.Parameters.Add(string.Format("@{0}", mParam.SourceColumn), mParam.SqlDbType, mParam.Size, mParam.SourceColumn); priKeyCount++; } if (updateColCount < needUpdateColName.Count && needUpdateColName.Contains(mParam.SourceColumn.ToUpper())) { dataAdapter.UpdateCommand.Parameters.Add(string.Format("@{0}", mParam.SourceColumn), mParam.SqlDbType, mParam.Size, mParam.SourceColumn); updateColCount++; } if (priKeyCount == prikeyColName.Count && updateColCount == needUpdateColName.Count) { break; } } dataAdapter.UpdateCommand.UpdatedRowSource = UpdateRowSource.None; } if (this.IsInTransaction) { dataAdapter.InsertCommand.Transaction = this.sqltrans; dataAdapter.UpdateCommand.Transaction = this.sqltrans; dataAdapter.DeleteCommand.Transaction = this.sqltrans; } result = dataAdapter.Update(dataSet, tableName); dataSet.AcceptChanges(); return result; } } catch (Exception e) { if (this.needLog) { StringBuilder sbparam = new StringBuilder(); sbparam.Append(tableName + ";\n"); Log.LogErr(sbparam.ToString(), e); } throw; } finally { if (!this.IsInTransaction && !this.KeepConnectionOpen) { this.sqlConn.Close(); } } } #endregion #region Dispose / Destructor public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose of remaining objects. if (this.sqlConn != null) { this.sqlConn.Close(); this.sqlConn.Dispose(); this.sqlConn = null; } if (this.sqltrans != null) { this.sqltrans.Dispose(); this.sqltrans = null; } } } #endregion } public class DBConnectParams { private string _server = string.Empty, _database = string.Empty, _userId = string.Empty, _password = string.Empty; private VerifyTypeEnum _verifyType = VerifyTypeEnum.Database; private int _maxPool = 100, _connectTimeout = 30000; /// <summary> /// New with Empty /// </summary> public DBConnectParams() { this._verifyType = VerifyTypeEnum.Windows; this._server = string.Empty; } /// <summary> /// New with VerifyTypeEnum.Windows /// </summary> /// <param name="strServer">serverName</param> /// <param name="strDB">database</param> public DBConnectParams(string strServer, string strDB) { this._verifyType = VerifyTypeEnum.Windows; this._server = strServer; this._database = strDB; } /// <summary> /// New with VerifyTypeEnum.Database /// </summary> /// <param name="strServer">servername</param> /// <param name="strDB">DataBase</param> /// <param name="strUserID">UserID</param> /// <param name="strPwd">UserPassword</param> public DBConnectParams(string strServer, string strDB, string strUserID, string strPwd) { this._verifyType = VerifyTypeEnum.Database; this._server = strServer; this._database = strDB; this._userId = strUserID; this._password = strPwd; } /// <summary> /// Data Source=*;Initial Catalog=*;Connect Timeout=0;Persist Security Info=True;User ID=*;Password=* /// </summary> /// <param name="connectionString">connectionString</param> public DBConnectParams(string connectionString) { if (string.IsNullOrEmpty(connectionString)) throw new Exception("Fail to get ConnectionString,Please check config file! "); else { MatchCollection matches = Regex.Matches(connectionString, @"(([^;=]+)=([^;=#]*))", RegexOptions.Compiled); if (!connectionString.ToLower().Contains("integrated security")) { foreach (Match m in matches) { switch (m.Groups[2].Value.ToLower().Trim()) { case "data source": case "server": this._server = m.Groups[3].Value; break; case "initial catalog": case "database": this._database = m.Groups[3].Value; break; case "user id": case "uid": this._userId = m.Groups[3].Value; break; case "password": this._password = m.Groups[3].Value; break; case "pwd": this._password = m.Groups[3].Value; break; } } if (string.IsNullOrEmpty(this._server) || string.IsNullOrEmpty(this._database) || string.IsNullOrEmpty(this._userId)) throw new Exception("Fail to get ConnectionString,Please check! "); this._verifyType = VerifyTypeEnum.Database; } else { foreach (Match m in matches) { switch (m.Groups[2].Value.ToLower().Trim()) { case "data source": case "server": this._server = m.Groups[3].Value; break; case "initial catalog": case "database": this._database = m.Groups[3].Value; break; } } if (string.IsNullOrEmpty(this._server) || string.IsNullOrEmpty(this._database)) throw new Exception("Fail to get ConnectionString,Please check! "); this._verifyType = VerifyTypeEnum.Windows; } } } public bool IsEmpty { get { return this._server.Equals(string.Empty); } } public VerifyTypeEnum VerifyType { get { return this._verifyType; } set { this._verifyType = value; } } public string Server { get { return this._server; } set { this._server = value; } } public string Database { get { return this._database; } set { this._database = value; } } public string UserID { get { return this._userId; } set { this._userId = value; } } public string Password { get { return this._password; } set { this._password = value; } } public int MaxPoolSize { get { return this._maxPool; } set { this._maxPool = value; } } public int ConnectTimeout { get { return this._connectTimeout; } set { this._connectTimeout = value; } } public override string ToString() { if (string.IsNullOrEmpty(this._database) || string.IsNullOrEmpty(this._server)) { return string.Empty; } if (this._verifyType == VerifyTypeEnum.Windows) { return string.Format("Integrated Security=SSPI;Persist Security Info=False;" + "Data Source={0};Initial Catalog={1};Connect Timeout={2};Max Pool Size={3}", this._server, this._database, this._connectTimeout, this._maxPool); } else { return string.Format("Data Source={0};Initial Catalog={1};User ID={2};Password={3};Connect Timeout={4};Max Pool Size={5} ", this._server, this._database, this._userId, this._password, this._connectTimeout, this._maxPool); } } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework.Storage; using ControlLibrary.MKI062V2; using System.Threading; namespace AngleEstimationApp_BetaRelease { /// <summary> /// This is the main type for your game /// </summary> public class Game : Microsoft.Xna.Framework.Game { private string COMport; INEMO2_Device dev= new INEMO2_Device(); GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Matrix worldMatrix; Matrix cameraMatrix; Matrix projectionMatrix; BasicEffect cubeEffect; BasicShape cube = new BasicShape(new Vector3(7, 5, 1), new Vector3(0, 0, 0)); Filter filter; Quaternion AuxFrame = new Quaternion((float)0, 0, (float)0, (float)1); Texture2D background; Rectangle mainFrame; int algorithm; int obsAlg; AcquisitionThread acq; Thread workerThread; Plot plotForm; private bool trend; public Game(int a,int b,int port,bool trend) { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; this.IsMouseVisible = true; this.algorithm = a; this.obsAlg = b; this.COMport = "PL=PL_001{PN=COM"+ (port+1)+ ", SENDMODE=B}"; switch (algorithm) { case 0: filter = new ComplementaryFilter(); break; case 1: filter = new QuaternionCF(); break; case 2: filter = new KalmanFilter(); break; default: filter = new KalmanFilter(); break; } filter.loadParameters(); filter.setObsMethod(obsAlg); this.Exiting += new EventHandler(Game1_Exiting); this.trend = trend; } void Game1_Exiting(object sender, EventArgs e) { acq.Disconnect(); Environment.Exit(0); } /// <summary> /// Allows the game to perform any initialization /// it needs to before starting to run. /// This is where it can query for any required /// services and load any non-graphic /// related content. Calling base. Initialize will /// enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { base.Initialize(); this.BeginRun(); initializeWorld(); //Connect to iNemo board acq = new AcquisitionThread(COMport, dev, this); workerThread = new Thread(acq.DoWork); workerThread.Start(); plotForm = new Plot(); if(trend) plotForm.Show(); } /// <summary> /// LoadContent will be called once /// per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // Load the background content. background = Content.Load<Texture2D>("Textures\\myback"); // Set the rectangle parameters. mainFrame = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); cube.shapeTexture = Content.Load<Texture2D>("Textures\\mytext"); } /// <summary> /// UnloadContent will be called once per game /// and is the place to unload all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic /// such as updating the world, /// checking for collisions, /// gathering input, and playing audio. /// </summary> /// <param name="gameTime"> /// Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); if (Mouse.GetState().RightButton == ButtonState.Pressed) graphics.ToggleFullScreen(); if (algorithm == 0) //Complementary filter { double[] anglesFiltered = new double[3]; anglesFiltered[0] = filter.getFilteredAngles()[0, 0]; anglesFiltered[1] = filter.getFilteredAngles()[1, 0]; anglesFiltered[2] = filter.getFilteredAngles()[2, 0]; Matrix m = Matrix.CreateRotationZ((float)(anglesFiltered[2] * Math.PI / 180)); Matrix m1 = Matrix.CreateRotationY(-(float)(anglesFiltered[1] * Math.PI / 180)); Matrix m2 = Matrix.CreateRotationX((float)(anglesFiltered[0] * Math.PI / 180)); Matrix m3 = m * m1 * m2; double qw = Math.Sqrt(1 + m3.M11 * m3.M11 + m3.M22 * m3.M22 + m3.M33 * m3.M33) / 2; double q1 = (m3.M32 - m3.M23) / (4 * qw); double q2 = (m3.M13 - m3.M31) / (4 * qw); double q3 = (m3.M21 - m3.M12) / (4 * qw); worldMatrix = Matrix.CreateFromQuaternion(AuxFrame * new Quaternion((float)q1, (float)q2, (float)q3, (float)qw)); } else { if (Mouse.GetState().LeftButton == ButtonState.Pressed) AuxFrame = new Quaternion(-(float)filter.getFilteredQuaternions()[1, 0], -(float)filter.getFilteredQuaternions()[2, 0], -(float)filter.getFilteredQuaternions()[3, 0], (float)filter.getFilteredQuaternions()[0, 0]); } base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime"> /// Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); // Draw the background. // Start building the sprite. spriteBatch.Begin(SpriteBlendMode.AlphaBlend); // Draw the background. spriteBatch.Draw(background, mainFrame, Color.White); // End building the sprite. spriteBatch.End(); cubeEffect.Begin(); if (algorithm == 0) //Complementary filter { double[] anglesFiltered = new double[3]; anglesFiltered[0] = filter.getFilteredAngles()[0, 0]; anglesFiltered[1] = filter.getFilteredAngles()[1, 0]; anglesFiltered[2] = filter.getFilteredAngles()[2, 0]; MatrixLibrary.Matrix anglesMatrix=new MatrixLibrary.Matrix(3,1); anglesMatrix[0,0]=anglesFiltered[0]; anglesMatrix[1,0]=anglesFiltered[1]; anglesMatrix[2,0]=anglesFiltered[2]; MatrixLibrary.Matrix q= MyQuaternion.getQuaternionFromAngles(anglesMatrix); worldMatrix = Matrix.CreateFromQuaternion(AuxFrame * new Quaternion((float)q[1, 0], -(float)q[2, 0], (float)q[3, 0], -(float)q[0, 0])); //worldMatrix = Matrix.CreateFromYawPitchRoll((float)(anglesFiltered[1] * Math.PI / 180), -(float)(anglesFiltered[0] * Math.PI / 180), -(float)(anglesFiltered[2] * Math.PI / 180)); } else { float q1=(float)filter.getFilteredQuaternions()[1, 0]; float q2=(float)filter.getFilteredQuaternions()[2, 0]; float q3=(float)filter.getFilteredQuaternions()[3, 0]; float q0=(float)filter.getFilteredQuaternions()[0, 0]; if(trend) plotForm.AddDataToGraph(q0,q1,q2,q3); worldMatrix = Matrix.CreateFromQuaternion(AuxFrame * new Quaternion(q1,q2,q3,q0)); } cubeEffect.World = worldMatrix; foreach (EffectPass pass in cubeEffect.CurrentTechnique.Passes) { pass.Begin(); cubeEffect.Texture = cube.shapeTexture; cube.RenderShape(GraphicsDevice); pass.End(); } cubeEffect.End(); base.Draw(gameTime); } public void initializeWorld() { cameraMatrix = Matrix.CreateLookAt(new Vector3(0, -30, 1), new Vector3(0, 0, 0), new Vector3(0, 1, 0)); projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, Window.ClientBounds.Width / Window.ClientBounds.Height, 1.0f, 50.0f); worldMatrix = Matrix.Identity; cubeEffect = new BasicEffect(GraphicsDevice, null); cubeEffect.World = worldMatrix; cubeEffect.View = cameraMatrix; cubeEffect.Projection = projectionMatrix; cubeEffect.TextureEnabled = true; } public void PacketReceived(INEMO2_FrameData data) { filter.filterStep(data.Gyroscope.X, data.Gyroscope.Y, data.Gyroscope.Z, data.Accelometer.X, data.Accelometer.Y, data.Accelometer.Z, data.Magnetometer.X, data.Magnetometer.Y, data.Magnetometer.Z); } } }
/* * Marshal.cs - Implementation of the * "System.Runtime.InteropServices.Marshal" class. * * Copyright (C) 2002 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Runtime.InteropServices { #if CONFIG_RUNTIME_INFRA using System; using System.Runtime.CompilerServices; using System.Reflection; using System.Threading; using System.Security; // This class is not ECMA-compatible, strictly speaking. But it is // usually necessary for any application that uses PInvoke or C. #if CONFIG_PERMISSIONS && !ECMA_COMPAT [SuppressUnmanagedCodeSecurity] #endif public sealed class Marshal { // This class cannot be instantiated. private Marshal() {} // Character size information. public static readonly int SystemDefaultCharSize = 1; public static readonly int SystemMaxDBCSCharSize = 6; // Allocate memory from the global (malloc) heap. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr AllocHGlobal(IntPtr cb); public static IntPtr AllocHGlobal(int cb) { return AllocHGlobal(new IntPtr(cb)); } // Internal version of "Copy" from managed to unmanaged. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void CopyMU(Array source, int startOffset, IntPtr destination, int numBytes); // Copy data from a managed array to an unmanaged memory pointer. public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex, destination, length); } public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 2, destination, length * 2); } public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 8, destination, length * 8); } public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 4, destination, length * 4); } public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 4, destination, length * 4); } public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 8, destination, length * 8); } public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { if(source == null) { throw new ArgumentNullException("source"); } if(destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > source.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (source.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyMU(source, startIndex * 2, destination, length * 2); } // Internal version of "Copy" from unmanaged to managed. [MethodImpl(MethodImplOptions.InternalCall)] extern private static void CopyUM(IntPtr source, Array destination, int startOffset, int numBytes); // Copy data from an unmanaged pointer to a managed array. public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex, length); } public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 2, length * 2); } public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 8, length * 8); } public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 4, length * 4); } public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 4, length * 4); } public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 8, length * 8); } public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { if(source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if(destination == null) { throw new ArgumentNullException("destination"); } if(startIndex < 0 || startIndex > destination.Length) { throw new ArgumentOutOfRangeException ("startIndex", _("ArgRange_Array")); } if(length < 0 || (destination.Length - startIndex) < length) { throw new ArgumentOutOfRangeException ("length", _("ArgRange_Array")); } CopyUM(source, destination, startIndex * 2, length * 2); } // Free memory that was allocated with AllocHGlobal. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void FreeHGlobal(IntPtr hglobal); // Get the offset of a field within a class. [MethodImpl(MethodImplOptions.InternalCall)] extern private static IntPtr OffsetOfInternal(Type t, String fieldName); public static IntPtr OffsetOf(Type t, String fieldName) { if(t == null) { throw new ArgumentNullException("t"); } else if(!(t is ClrType)) { throw new ArgumentException(_("Arg_MustBeType"), "t"); } if(fieldName == null) { throw new ArgumentNullException("fieldName"); } IntPtr offset = OffsetOfInternal(t, fieldName); if(offset == new IntPtr(-1)) { throw new ArgumentException (_("Reflection_UnknownField"), "fieldName"); } return offset; } // Convert a pointer to an ANSI string into a string object. [MethodImpl(MethodImplOptions.InternalCall)] extern private static String PtrToStringAnsiInternal(IntPtr ptr, int len); public static String PtrToStringAnsi(IntPtr ptr) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else { return PtrToStringAnsiInternal(ptr, -1); } } public static String PtrToStringAnsi(IntPtr ptr, int len) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else if(len < 0) { throw new ArgumentException(_("ArgRange_NonNegative")); } else { return PtrToStringAnsiInternal(ptr, len); } } // Convert a pointer to an Auto string into a string object. // In this implementation, "Auto" is UTF-8. [MethodImpl(MethodImplOptions.InternalCall)] extern private static String PtrToStringAutoInternal(IntPtr ptr, int len); public static String PtrToStringAuto(IntPtr ptr) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else { return PtrToStringAutoInternal(ptr, -1); } } public static String PtrToStringAuto(IntPtr ptr, int len) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else if(len < 0) { throw new ArgumentException(_("ArgRange_NonNegative")); } else { return PtrToStringAutoInternal(ptr, len); } } // Convert a pointer to a Unicode string into a string object. [MethodImpl(MethodImplOptions.InternalCall)] extern private static String PtrToStringUniInternal(IntPtr ptr, int len); public static String PtrToStringUni(IntPtr ptr) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else { return PtrToStringUniInternal(ptr, -1); } } public static String PtrToStringUni(IntPtr ptr, int len) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else if(len < 0) { throw new ArgumentException(_("ArgRange_NonNegative")); } else { return PtrToStringUniInternal(ptr, len); } } // Convert the data at an unmanaged pointer location into // an object by marshalling its fields one by one. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool PtrToStructureInternal (IntPtr ptr, Object structure, bool allowValueTypes); public static void PtrToStructure(IntPtr ptr, Object structure) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else if(structure == null) { throw new ArgumentNullException("structure"); } if(!PtrToStructureInternal(ptr, structure, false)) { throw new ArgumentException (_("Arg_CannotMarshalStruct")); } } #if CONFIG_REFLECTION public static Object PtrToStructure(IntPtr ptr, Type structureType) { if(ptr == IntPtr.Zero) { return null; } else if(structureType == null) { throw new ArgumentNullException("structureType"); } else if(!(structureType is ClrType)) { throw new ArgumentException (_("Arg_MustBeType"), "structureType"); } Object obj = Activator.CreateInstance(structureType); if(!PtrToStructureInternal(ptr, obj, true)) { throw new ArgumentException (_("Arg_CannotMarshalStruct")); } return obj; } #endif // Destroy the contents of an unmanaged structure. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool DestroyStructureInternal (IntPtr ptr, Type structureType); public static void DestroyStructure(IntPtr ptr, Type structureType) { if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } else if(structureType == null) { throw new ArgumentNullException("structureType"); } else if(!(structureType is ClrType)) { throw new ArgumentException (_("Arg_MustBeType"), "structureType"); } if(!DestroyStructureInternal(ptr, structureType)) { throw new ArgumentException (_("Arg_CannotMarshalStruct")); } } // Convert an object into an unmanaged structure. [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool StructureToPtrInternal (Object structure, IntPtr ptr); public static void StructureToPtr(Object structure, IntPtr ptr, bool fDeleteOld) { if(structure == null) { throw new ArgumentNullException("structure"); } else if(ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } if(!StructureToPtrInternal(structure, ptr)) { throw new ArgumentException (_("Arg_CannotMarshalStruct")); } if(fDeleteOld) { DestroyStructure(ptr, structure.GetType()); } } // Convert an object into a pointer to its first byte. [MethodImpl(MethodImplOptions.InternalCall)] extern private static IntPtr ObjectToPtr(Object obj); // Read a byte from an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static byte ReadByte(IntPtr ptr, int ofs); public static byte ReadByte(IntPtr ptr) { return ReadByte(ptr, 0); } public static byte ReadByte(Object ptr, int ofs) { return ReadByte(ObjectToPtr(ptr), ofs); } // Read a 16-bit integer from an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static short ReadInt16(IntPtr ptr, int ofs); public static short ReadInt16(IntPtr ptr) { return ReadInt16(ptr, 0); } public static short ReadInt16(Object ptr, int ofs) { return ReadInt16(ObjectToPtr(ptr), ofs); } // Read a 32-bit integer from an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static int ReadInt32(IntPtr ptr, int ofs); public static int ReadInt32(IntPtr ptr) { return ReadInt32(ptr, 0); } public static int ReadInt32(Object ptr, int ofs) { return ReadInt32(ObjectToPtr(ptr), ofs); } // Read a 64-bit integer from an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static long ReadInt64(IntPtr ptr, int ofs); public static long ReadInt64(IntPtr ptr) { return ReadInt64(ptr, 0); } public static long ReadInt64(Object ptr, int ofs) { return ReadInt64(ObjectToPtr(ptr), ofs); } // Read a native pointer from an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr ReadIntPtr(IntPtr ptr, int ofs); public static IntPtr ReadIntPtr(IntPtr ptr) { return ReadIntPtr(ptr, 0); } public static IntPtr ReadIntPtr(Object ptr, int ofs) { return ReadIntPtr(ObjectToPtr(ptr), ofs); } // Reallocate memory that was allocated with AllocHGlobal. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb); // Get the size of a type. [MethodImpl(MethodImplOptions.InternalCall)] extern private static int SizeOfInternal(Type t); public static int SizeOf(Type t) { if(t == null) { throw new ArgumentNullException("t"); } else if(!(t is ClrType)) { throw new ArgumentException(_("Arg_MustBeType"), "t"); } else { return SizeOfInternal(t); } } // Get the size of an object. public static int SizeOf(Object o) { if(o == null) { throw new ArgumentNullException("o"); } return SizeOf(o.GetType()); } // Convert a string into an ANSI character buffer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr StringToHGlobalAnsi(String s); // Convert a string into an Auto character buffer. // In this implementation, "Auto" is UTF-8. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr StringToHGlobalAuto(String s); // Convert a string into a Unicode character buffer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr StringToHGlobalUni(String s); // Get the address of a pinned array element. [MethodImpl(MethodImplOptions.InternalCall)] extern public static IntPtr UnsafeAddrOfPinnedArrayElement (Array arr, int index); // Write a byte to an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void WriteByte(IntPtr ptr, int ofs, byte val); public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } public static void WriteByte(Object ptr, int ofs, byte val) { WriteByte(ObjectToPtr(ptr), ofs, val); } // Write a 16-bit integer to an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void WriteInt16(IntPtr ptr, int ofs, short val); public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); } public static void WriteInt16(Object ptr, int ofs, short val) { WriteInt16(ObjectToPtr(ptr), ofs, val); } // Write a 16-bit integer (as a char) to an unmanaged pointer. public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } public static void WriteInt16(Object ptr, int ofs, char val) { WriteInt16(ObjectToPtr(ptr), ofs, (short)val); } // Write a 32-bit integer to an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void WriteInt32(IntPtr ptr, int ofs, int val); public static void WriteInt32(IntPtr ptr, int val) { WriteInt32(ptr, 0, val); } public static void WriteInt32(Object ptr, int ofs, int val) { WriteInt32(ObjectToPtr(ptr), ofs, val); } // Write a 64-bit integer to an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void WriteInt64(IntPtr ptr, int ofs, long val); public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); } public static void WriteInt64(Object ptr, int ofs, long val) { WriteInt64(ObjectToPtr(ptr), ofs, val); } // Write a native pointer to an unmanaged pointer. [MethodImpl(MethodImplOptions.InternalCall)] extern public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val); public static void WriteIntPtr(IntPtr ptr, IntPtr val) { WriteIntPtr(ptr, 0, val); } public static void WriteIntPtr(Object ptr, int ofs, IntPtr val) { WriteIntPtr(ObjectToPtr(ptr), ofs, val); } #if CONFIG_COM_INTEROP // Stub out COM-related methods, which are not supported // in this implementation. public static int AddRef(IntPtr pUnk) { throw new NotImplementedException(); } public static IntPtr AllocCoTaskMem(int cb) { throw new NotImplementedException(); } public static Object BindToMoniker(String monikerName) { throw new NotImplementedException(); } public static void ChangeWrapperHandleStrength(Object otp, bool fIsWeak) { throw new NotImplementedException(); } public static Object CreateWrapperOfType(Object o, Type t) { throw new NotImplementedException(); } public static void FreeCoTaskMem(IntPtr ptr) { throw new NotImplementedException(); } public static Guid GenerateGuidForType(Type type) { throw new NotImplementedException(); } public static String GenerateProgIdForType(Type type) { throw new NotImplementedException(); } public static Object GetActiveObject(String progID) { throw new NotImplementedException(); } public static IntPtr GetComInterfaceForObject(Object o, Type T) { throw new NotImplementedException(); } public static Object GetComObjectData(Object obj, Object key) { throw new NotImplementedException(); } #if CONFIG_REFLECTION public static int GetComSlotForMethodInfo(MemberInfo m) { throw new NotImplementedException(); } #endif public static int GetEndComSlot(Type t) { throw new NotImplementedException(); } public static IntPtr GetIDispatchForObject(Object o) { throw new NotImplementedException(); } public static IntPtr GetITypeInfoForType(Type t) { throw new NotImplementedException(); } public static IntPtr GetIUnknownForObject(Object o) { throw new NotImplementedException(); } #if !ECMA_COMPAT && CONFIG_REFLECTION public static MemberInfo GetMethodInfoForComSlot (Type t, int slot, ref ComMemberType memberType) { throw new NotImplementedException(); } #endif public static Object GetObjectForIUnknown(IntPtr pUnk) { throw new NotImplementedException(); } public static Object[] GetObjectsForNativeVariants (IntPtr aSrcNativeVariant, int cVars) { throw new NotImplementedException(); } public static int GetStartComSlot(Type t) { throw new NotImplementedException(); } public static Object GetTypedObjectForIUnknown(IntPtr pUnk, Type t) { throw new NotImplementedException(); } public static Type GetTypeForITypeInfo(IntPtr piTypeInfo) { throw new NotImplementedException(); } public static String GetTypeInfoName(UCOMITypeInfo pTI) { throw new NotImplementedException(); } public static Guid GetTypeLibGuid(UCOMITypeLib pTLB) { throw new NotImplementedException(); } public static Guid GetTypeLibGuidForAssembly(Assembly asm) { throw new NotImplementedException(); } public static int GetTypeLibLcid(UCOMITypeLib pTLB) { throw new NotImplementedException(); } public static String GetTypeLibName(UCOMITypeLib pTLB) { throw new NotImplementedException(); } public static bool IsComObject(Object o) { return false; } public static bool IsTypeVisibleFromCom(Type t) { return false; } public static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv) { throw new NotImplementedException(); } public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb) { throw new NotImplementedException(); } public static int Release(IntPtr pUnk) { throw new NotImplementedException(); } public static int ReleaseComObject(Object o) { throw new NotImplementedException(); } public static void ReleaseThreadCache() { throw new NotImplementedException(); } public static bool SetComObjectData(Object obj, Object key, Object data) { throw new NotImplementedException(); } public static IntPtr StringToCoTaskMemAnsi(String s) { throw new NotImplementedException(); } public static IntPtr StringToCoTaskMemAuto(String s) { throw new NotImplementedException(); } public static IntPtr StringToCoTaskMemUni(String s) { throw new NotImplementedException(); } public static void ThrowExceptionForHR(int errorCode) { throw new NotImplementedException(); } public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { throw new NotImplementedException(); } #endif // CONFIG_COM_INTEROP // Other methods that aren't relevant to this implementation. public static void FreeBSTR(IntPtr str) { throw new NotImplementedException(); } public static int GetExceptionCode() { throw new NotImplementedException(); } public static IntPtr GetExceptionPointers() { throw new NotImplementedException(); } #if CONFIG_REFLECTION public static IntPtr GetHINSTANCE(Module m) { throw new NotImplementedException(); } #endif public static int GetHRForException(Exception e) { throw new NotImplementedException(); } public static int GetHRForLastWin32Error() { throw new NotImplementedException(); } public static int GetLastWin32Error() { throw new NotImplementedException(); } public static IntPtr GetManagedThunkForUnmanagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature) { throw new NotImplementedException(); } public static void GetNativeVariantForObject (Object obj, IntPtr pDstNativeVariant) { throw new NotImplementedException(); } public static Object GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { throw new NotImplementedException(); } public static Thread GetThreadFromFiberCookie(int cookie) { throw new NotImplementedException(); } public static IntPtr GetUnmanagedThunkForManagedMethodPtr (IntPtr pfnMethodToWrap, IntPtr pbSignature, int cbSignature) { throw new NotImplementedException(); } #if CONFIG_REFLECTION public static int NumParamBytes(MethodInfo m) { throw new NotImplementedException(); } public static void Prelink(MethodInfo m) { throw new NotImplementedException(); } #endif public static void PrelinkAll(Type c) { throw new NotImplementedException(); } public static String PtrToStringBSTR(IntPtr ptr) { throw new NotImplementedException(); } public static IntPtr StringToBSTR(String s) { throw new NotImplementedException(); } }; // class Marshal #endif // CONFIG_RUNTIME_INFRA }; // namespace System.Runtime.InteropServices
/******************************************************************************* * Copyright 2008-2013 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. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Route Table /// </summary> [XmlRootAttribute(IsNullable = false)] public class RouteTable { private string routeTableIdField; private string vpcIdField; private List<Route> routesField; private List<RouteTableAssociation> associationsField; private List<Tag> tagField; private List<string> propagatingVpnGatewaysField; private List<PropagatedRoute> propagatedRoutesField; /// <summary> /// The route table's ID. /// </summary> [XmlElementAttribute(ElementName = "RouteTableId")] public string RouteTableId { get { return this.routeTableIdField; } set { this.routeTableIdField = value; } } /// <summary> /// Sets the route table's ID. /// </summary> /// <param name="routeTableId">The route table's ID.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithRouteTableId(string routeTableId) { this.routeTableIdField = routeTableId; return this; } /// <summary> /// Checks if RouteTableId property is set /// </summary> /// <returns>true if RouteTableId property is set</returns> public bool IsSetRouteTableId() { return this.routeTableIdField != null; } /// <summary> /// The ID of the VPC the route table is in. /// </summary> [XmlElementAttribute(ElementName = "VpcId")] public string VpcId { get { return this.vpcIdField; } set { this.vpcIdField = value; } } /// <summary> /// Sets the ID of the VPC the route table is in. /// </summary> /// <param name="vpcId">The ID of the VPC the route table is in.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithVpcId(string vpcId) { this.vpcIdField = vpcId; return this; } /// <summary> /// Checks if VpcId property is set /// </summary> /// <returns>true if VpcId property is set</returns> public bool IsSetVpcId() { return this.vpcIdField != null; } /// <summary> /// A list of routes in the route table. /// </summary> [XmlElementAttribute(ElementName = "Routes")] public List<Route> Routes { get { if (this.routesField == null) { this.routesField = new List<Route>(); } return this.routesField; } set { this.routesField = value; } } /// <summary> /// Sets the list of routes in the route table. /// </summary> /// <param name="list">A list of routes in the route table.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithRoutes(params Route[] list) { foreach (Route item in list) { Routes.Add(item); } return this; } /// <summary> /// Checks if Routes property is set /// </summary> /// <returns>true if Routes property is set</returns> public bool IsSetRoutes() { return (Routes.Count > 0); } /// <summary> /// A list of associations between the route table and one or more subnets. /// </summary> [XmlElementAttribute(ElementName = "Associations")] public List<RouteTableAssociation> Associations { get { if (this.associationsField == null) { this.associationsField = new List<RouteTableAssociation>(); } return this.associationsField; } set { this.associationsField = value; } } /// <summary> /// Sets the associations between the route table and one or more subnets. /// </summary> /// <param name="list">A list of associations between the route table and one or more /// subnets.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithAssociations(params RouteTableAssociation[] list) { foreach (RouteTableAssociation item in list) { Associations.Add(item); } return this; } /// <summary> /// Checks if Associations property is set /// </summary> /// <returns>true if Associations property is set</returns> public bool IsSetAssociations() { return (Associations.Count > 0); } /// <summary> /// A list of tags for the RouteTable. /// </summary> [XmlElementAttribute(ElementName = "Tag")] public List<Tag> Tag { get { if (this.tagField == null) { this.tagField = new List<Tag>(); } return this.tagField; } set { this.tagField = value; } } /// <summary> /// Sets the tags for the RouteTable. /// </summary> /// <param name="list">A list of tags for the RouteTable.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithTag(params Tag[] list) { foreach (Tag item in list) { Tag.Add(item); } return this; } /// <summary> /// Checks if Tag property is set /// </summary> /// <returns>true if Tag property is set</returns> public bool IsSetTag() { return (Tag.Count > 0); } /// <summary> /// DOCS_TODO /// </summary> [XmlElementAttribute(ElementName = "PropagatingVpnGateway")] public List<string> PropagatingVpnGateways { get { if (this.propagatingVpnGatewaysField == null) { this.propagatingVpnGatewaysField = new List<string>(); } return this.propagatingVpnGatewaysField; } set { this.propagatingVpnGatewaysField = value; } } /// <summary> /// DOCS_TODO /// </summary> /// <param name="list"></param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithPropagatingVpnGateways(params string[] list) { foreach (string item in list) { this.PropagatingVpnGateways.Add(item); } return this; } /// <summary> /// Checks if the PropagatingVpnGateways property is set. /// </summary> /// <returns>True if the property is set</returns> public bool IsSetPropagatingVpnGateways() { return (this.PropagatingVpnGateways.Count > 0); } /// <summary> /// DOCS_TODO /// </summary> [XmlElementAttribute(ElementName = "PropagatedRoute")] public List<PropagatedRoute> PropagatedRoutes { get { if (this.propagatedRoutesField == null) { this.propagatedRoutesField = new List<PropagatedRoute>(); } return this.propagatedRoutesField; } set { this.propagatedRoutesField = value; } } /// <summary> /// DOCS_TODO /// </summary> /// <param name="list"></param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RouteTable WithPropagatedRoutes(params PropagatedRoute[] list) { foreach (PropagatedRoute item in list) { this.PropagatedRoutes.Add(item); } return this; } /// <summary> /// Checks if the PropagatedRoutes property is set /// </summary> /// <returns>True if the property is set</returns> public bool IsSetPropagatedRoutes() { return (this.PropagatedRoutes.Count > 0); } } }
// 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.AcceptanceTestsBodyDictionary { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; /// <summary> /// Dictionary operations. /// </summary> public partial interface IDictionary { /// <summary> /// Get null dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutEmptyWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullValueWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with null key /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetNullKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get Dictionary with key as empty string /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetEmptyStringKeyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get invalid Dictionary value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanTfftWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": true, "1": false, "2": false, /// "3": true } /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutBooleanTfftWithHttpMessagesAsync(IDictionary<string, bool?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": true, "1": null, "2": false } /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value '{"0": true, "1": "boolean", "2": /// false}' /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, bool?>>> GetBooleanInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntegerValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutIntegerValidWithHttpMessagesAsync(IDictionary<string, int?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, int?>>> GetIntInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutLongValidWithHttpMessagesAsync(IDictionary<string, long?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": null, "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get long dictionary value {"0": 1, "1": "integer", "2": 0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, long?>>> GetLongInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutFloatValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetFloatInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDoubleValidWithHttpMessagesAsync(IDictionary<string, double?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, double?>>> GetDoubleInvalidStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutStringValidWithHttpMessagesAsync(IDictionary<string, string> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": null, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, string>>> GetStringWithInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get integer dictionary value {"0": "2000-12-01", "1": /// "1980-01-02", "2": "1492-10-12"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": /// "1492-10-12"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2012-01-01", "1": null, "2": /// "1776-07-04"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2011-03-22", "1": "date"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "1980-01-02T00:11:35+01:00", "2": "1492-10-12T10:15:01-08:00"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": /// "date-time"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeInvalidCharsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 /// 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, /// 12 Oct 1492 10:15:01 GMT"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, DateTime?>>> GetDateTimeRfc1123ValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", /// "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 /// 10:15:01 GMT"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDateTimeRfc1123ValidWithHttpMessagesAsync(IDictionary<string, DateTime?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": /// "P5DT1H0M0S"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, TimeSpan?>>> GetDurationValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Set dictionary value {"0": "P123DT22H14M12.011S", "1": /// "P5DT1H0M0S"} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDurationValidWithHttpMessagesAsync(IDictionary<string, TimeSpan?> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each item encoded in base64 /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 /// 03), "2": hex (25, 29, 43)} with each elementencoded in base 64 /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutByteValidWithHttpMessagesAsync(IDictionary<string, byte[]> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with /// the first item base64 encoded /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get base64url dictionary value {"0": "a string that gets encoded /// with base64url", "1": "test string", "2": "Lorem ipsum"} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, byte[]>>> GetBase64UrlWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type null value /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get empty dictionary of complex type {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with null item {"0": {"integer": 1, /// "string": "2"}, "1": null, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with empty item {"0": {"integer": /// 1, "string": "2"}, "1:" {}, "2": {"integer": 5, "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get dictionary of complex type with {"0": {"integer": 1, "string": /// "2"}, "1": {"integer": 3, "string": "4"}, "2": {"integer": 5, /// "string": "6"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, Widget>>> GetComplexValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put an dictionary of complex type with values {"0": {"integer": 1, /// "string": "2"}, "1": {"integer": 3, "string": "4"}, "2": /// {"integer": 5, "string": "6"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutComplexValidWithHttpMessagesAsync(IDictionary<string, Widget> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get a null array /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an empty dictionary {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": /// null, "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], /// "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IList<string>>>> GetArrayValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", /// "5", "6"], "2": ["7", "8", "9"]} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutArrayValidWithHttpMessagesAsync(IDictionary<string, IList<string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries with value null /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// null, "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": {}, /// "2": {"7": "seven", "8": "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryItemEmptyWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse<IDictionary<string, IDictionary<string, string>>>> GetDictionaryValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get an dictionaries of dictionaries of type &lt;string, string&gt; /// with value {"0": {"1": "one", "2": "two", "3": "three"}, "1": /// {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": /// "eight", "9": "nine"}} /// </summary> /// <param name='arrayBody'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<HttpOperationResponse> PutDictionaryValidWithHttpMessagesAsync(IDictionary<string, IDictionary<string, string>> arrayBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace fyiReporting.RdlDesign { /// <summary> /// Summary description for StyleCtl. /// </summary> partial class DataSetsCtl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DataSetsCtl)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.tbTimeout = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.bRefresh = new System.Windows.Forms.Button(); this.bEditSQL = new System.Windows.Forms.Button(); this.tbSQL = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.cbDataSource = new System.Windows.Forms.ComboBox(); this.lDataSource = new System.Windows.Forms.Label(); this.tbDSName = new System.Windows.Forms.TextBox(); this.lDataSetName = new System.Windows.Forms.Label(); this.bDeleteField = new System.Windows.Forms.Button(); this.dgFields = new System.Windows.Forms.DataGridView(); this.dgtbName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgtbQueryName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgtbValue = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dgtbTypeName = new System.Windows.Forms.DataGridViewComboBoxColumn(); this.label2 = new System.Windows.Forms.Label(); this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.tbTimeout)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dgFields)).BeginInit(); this.SuspendLayout(); // // splitContainer1 // resources.ApplyResources(this.splitContainer1, "splitContainer1"); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.tbTimeout); this.splitContainer1.Panel1.Controls.Add(this.label3); this.splitContainer1.Panel1.Controls.Add(this.bRefresh); this.splitContainer1.Panel1.Controls.Add(this.bEditSQL); this.splitContainer1.Panel1.Controls.Add(this.tbSQL); this.splitContainer1.Panel1.Controls.Add(this.label1); this.splitContainer1.Panel1.Controls.Add(this.cbDataSource); this.splitContainer1.Panel1.Controls.Add(this.lDataSource); this.splitContainer1.Panel1.Controls.Add(this.tbDSName); this.splitContainer1.Panel1.Controls.Add(this.lDataSetName); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this.bDeleteField); this.splitContainer1.Panel2.Controls.Add(this.dgFields); this.splitContainer1.Panel2.Controls.Add(this.label2); // // tbTimeout // resources.ApplyResources(this.tbTimeout, "tbTimeout"); this.tbTimeout.Maximum = new decimal(new int[] { 2147483647, 0, 0, 0}); this.tbTimeout.Name = "tbTimeout"; this.tbTimeout.ValueChanged += new System.EventHandler(this.tbTimeout_ValueChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // bRefresh // resources.ApplyResources(this.bRefresh, "bRefresh"); this.bRefresh.Name = "bRefresh"; this.bRefresh.Click += new System.EventHandler(this.bRefresh_Click); // // bEditSQL // resources.ApplyResources(this.bEditSQL, "bEditSQL"); this.bEditSQL.Name = "bEditSQL"; this.bEditSQL.Click += new System.EventHandler(this.bEditSQL_Click); // // tbSQL // this.tbSQL.AcceptsReturn = true; this.tbSQL.AcceptsTab = true; resources.ApplyResources(this.tbSQL, "tbSQL"); this.tbSQL.Name = "tbSQL"; this.tbSQL.TextChanged += new System.EventHandler(this.tbSQL_TextChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // cbDataSource // resources.ApplyResources(this.cbDataSource, "cbDataSource"); this.cbDataSource.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSource.Name = "cbDataSource"; this.cbDataSource.SelectedIndexChanged += new System.EventHandler(this.cbDataSource_SelectedIndexChanged); // // lDataSource // resources.ApplyResources(this.lDataSource, "lDataSource"); this.lDataSource.Name = "lDataSource"; // // tbDSName // resources.ApplyResources(this.tbDSName, "tbDSName"); this.tbDSName.Name = "tbDSName"; this.tbDSName.TextChanged += new System.EventHandler(this.tbDSName_TextChanged); // // lDataSetName // resources.ApplyResources(this.lDataSetName, "lDataSetName"); this.lDataSetName.Name = "lDataSetName"; // // bDeleteField // resources.ApplyResources(this.bDeleteField, "bDeleteField"); this.bDeleteField.Name = "bDeleteField"; this.bDeleteField.Click += new System.EventHandler(this.bDeleteField_Click); // // dgFields // resources.ApplyResources(this.dgFields, "dgFields"); this.dgFields.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.ControlText; dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dgFields.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dgFields.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.dgtbName, this.dgtbQueryName, this.dgtbValue, this.dgtbTypeName}); this.dgFields.Name = "dgFields"; // // dgtbName // this.dgtbName.DataPropertyName = "Name"; resources.ApplyResources(this.dgtbName, "dgtbName"); this.dgtbName.Name = "dgtbName"; // // dgtbQueryName // this.dgtbQueryName.DataPropertyName = "QueryName"; resources.ApplyResources(this.dgtbQueryName, "dgtbQueryName"); this.dgtbQueryName.Name = "dgtbQueryName"; // // dgtbValue // this.dgtbValue.DataPropertyName = "Value"; resources.ApplyResources(this.dgtbValue, "dgtbValue"); this.dgtbValue.Name = "dgtbValue"; // // dgtbTypeName // this.dgtbTypeName.DataPropertyName = "TypeName"; resources.ApplyResources(this.dgtbTypeName, "dgtbTypeName"); this.dgtbTypeName.Items.AddRange(new object[] { "System.String", "System.Int16", "System.Int32", "System.Int64", "System.UInt16", "System.UInt32", "System.UInt64", "System.Single", "System.Double", "System.Decimal", "System.DateTime", "System.Char", "System.Boolean", "System.Byte"}); this.dgtbTypeName.Name = "dgtbTypeName"; this.dgtbTypeName.Resizable = System.Windows.Forms.DataGridViewTriState.True; this.dgtbTypeName.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // dataGridTableStyle1 // this.dataGridTableStyle1.DataGrid = null; this.dataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText; // // DataSetsCtl // this.Controls.Add(this.splitContainer1); this.MinimumSize = new System.Drawing.Size(480, 300); this.Name = "DataSetsCtl"; resources.ApplyResources(this, "$this"); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel1.PerformLayout(); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.tbTimeout)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dgFields)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.NumericUpDown tbTimeout; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button bRefresh; private System.Windows.Forms.Button bEditSQL; private System.Windows.Forms.TextBox tbSQL; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cbDataSource; private System.Windows.Forms.Label lDataSource; private System.Windows.Forms.TextBox tbDSName; private System.Windows.Forms.Label lDataSetName; private System.Windows.Forms.Button bDeleteField; private System.Windows.Forms.DataGridView dgFields; private System.Windows.Forms.Label label2; private System.Windows.Forms.DataGridViewTextBoxColumn dgtbName; private System.Windows.Forms.DataGridViewTextBoxColumn dgtbQueryName; private System.Windows.Forms.DataGridViewTextBoxColumn dgtbValue; private System.Windows.Forms.DataGridViewComboBoxColumn dgtbTypeName; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace System { // The Parse methods provided by the numeric classes convert a // string to a numeric value. The optional style parameter specifies the // permitted style of the numeric string. It must be a combination of bit flags // from the NumberStyles enumeration. The optional info parameter // specifies the NumberFormatInfo instance to use when parsing the // string. If the info parameter is null or omitted, the numeric // formatting information is obtained from the current culture. // // Numeric strings produced by the Format methods using the Currency, // Decimal, Engineering, Fixed point, General, or Number standard formats // (the C, D, E, F, G, and N format specifiers) are guaranteed to be parseable // by the Parse methods if the NumberStyles.Any style is // specified. Note, however, that the Parse methods do not accept // NaNs or Infinities. internal partial class Number { private const int Int32Precision = 10; private const int UInt32Precision = Int32Precision; private const int Int64Precision = 19; private const int UInt64Precision = 20; private static bool HexNumberToInt32(ref NumberBuffer number, ref int value) { uint passedValue = 0; bool returnValue = HexNumberToUInt32(ref number, ref passedValue); value = (int)passedValue; return returnValue; } private static bool HexNumberToInt64(ref NumberBuffer number, ref long value) { ulong passedValue = 0; bool returnValue = HexNumberToUInt64(ref number, ref passedValue); value = (long)passedValue; return returnValue; } private static unsafe bool HexNumberToUInt32(ref NumberBuffer number, ref uint value) { int i = number.scale; if (i > UInt32Precision || i < number.precision) { return false; } char* p = number.digits; Debug.Assert(p != null); uint n = 0; while (--i >= 0) { if (n > ((uint)0xFFFFFFFF / 16)) { return false; } n *= 16; if (*p != '\0') { uint newN = n; if (*p != '\0') { if (*p >= '0' && *p <= '9') { newN += (uint)(*p - '0'); } else { if (*p >= 'A' && *p <= 'F') { newN += (uint)((*p - 'A') + 10); } else { Debug.Assert(*p >= 'a' && *p <= 'f'); newN += (uint)((*p - 'a') + 10); } } p++; } // Detect an overflow here... if (newN < n) { return false; } n = newN; } } value = n; return true; } private static unsafe bool HexNumberToUInt64(ref NumberBuffer number, ref ulong value) { int i = number.scale; if (i > UInt64Precision || i < number.precision) { return false; } char* p = number.digits; Debug.Assert(p != null); ulong n = 0; while (--i >= 0) { if (n > (0xFFFFFFFFFFFFFFFF / 16)) { return false; } n *= 16; if (*p != '\0') { ulong newN = n; if (*p != '\0') { if (*p >= '0' && *p <= '9') { newN += (ulong)(*p - '0'); } else { if (*p >= 'A' && *p <= 'F') { newN += (ulong)((*p - 'A') + 10); } else { Debug.Assert(*p >= 'a' && *p <= 'f'); newN += (ulong)((*p - 'a') + 10); } } p++; } // Detect an overflow here... if (newN < n) { return false; } n = newN; } } value = n; return true; } private static unsafe bool NumberToInt32(ref NumberBuffer number, ref int value) { int i = number.scale; if (i > Int32Precision || i < number.precision) { return false; } char* p = number.digits; Debug.Assert(p != null); int n = 0; while (--i >= 0) { if ((uint)n > (0x7FFFFFFF / 10)) { return false; } n *= 10; if (*p != '\0') { n += (int)(*p++ - '0'); } } if (number.sign) { n = -n; if (n > 0) { return false; } } else { if (n < 0) { return false; } } value = n; return true; } private static unsafe bool NumberToInt64(ref NumberBuffer number, ref long value) { int i = number.scale; if (i > Int64Precision || i < number.precision) { return false; } char* p = number.digits; Debug.Assert(p != null); long n = 0; while (--i >= 0) { if ((ulong)n > (0x7FFFFFFFFFFFFFFF / 10)) { return false; } n *= 10; if (*p != '\0') { n += (int)(*p++ - '0'); } } if (number.sign) { n = -n; if (n > 0) { return false; } } else { if (n < 0) { return false; } } value = n; return true; } private static unsafe bool NumberToUInt32(ref NumberBuffer number, ref uint value) { int i = number.scale; if (i > UInt32Precision || i < number.precision || number.sign) { return false; } char* p = number.digits; Debug.Assert(p != null); uint n = 0; while (--i >= 0) { if (n > (0xFFFFFFFF / 10)) { return false; } n *= 10; if (*p != '\0') { uint newN = n + (uint)(*p++ - '0'); // Detect an overflow here... if (newN < n) { return false; } n = newN; } } value = n; return true; } private static unsafe bool NumberToUInt64(ref NumberBuffer number, ref ulong value) { int i = number.scale; if (i > UInt64Precision || i < number.precision || number.sign) { return false; } char* p = number.digits; Debug.Assert(p != null); ulong n = 0; while (--i >= 0) { if (n > (0xFFFFFFFFFFFFFFFF / 10)) { return false; } n *= 10; if (*p != '\0') { ulong newN = n + (ulong)(*p++ - '0'); // Detect an overflow here... if (newN < n) { return false; } n = newN; } } value = n; return true; } internal static unsafe int ParseInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { NumberBuffer number = default; int i = 0; StringToNumber(s, style, ref number, info, false); if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToInt32(ref number, ref i)) { throw new OverflowException(SR.Overflow_Int32); } } else { if (!NumberToInt32(ref number, ref i)) { throw new OverflowException(SR.Overflow_Int32); } } return i; } internal static unsafe long ParseInt64(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; long i = 0; StringToNumber(value, options, ref number, numfmt, false); if ((options & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToInt64(ref number, ref i)) { throw new OverflowException(SR.Overflow_Int64); } } else { if (!NumberToInt64(ref number, ref i)) { throw new OverflowException(SR.Overflow_Int64); } } return i; } internal static unsafe uint ParseUInt32(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; uint i = 0; StringToNumber(value, options, ref number, numfmt, false); if ((options & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToUInt32(ref number, ref i)) { throw new OverflowException(SR.Overflow_UInt32); } } else { if (!NumberToUInt32(ref number, ref i)) { throw new OverflowException(SR.Overflow_UInt32); } } return i; } internal static unsafe ulong ParseUInt64(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; ulong i = 0; StringToNumber(value, options, ref number, numfmt, false); if ((options & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToUInt64(ref number, ref i)) { throw new OverflowException(SR.Overflow_UInt64); } } else { if (!NumberToUInt64(ref number, ref i)) { throw new OverflowException(SR.Overflow_UInt64); } } return i; } private static unsafe bool ParseNumber(ref char* str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal) { const int StateSign = 0x0001; const int StateParens = 0x0002; const int StateDigits = 0x0004; const int StateNonZero = 0x0008; const int StateDecimal = 0x0010; const int StateCurrency = 0x0020; number.scale = 0; number.sign = false; string decSep; // decimal separator from NumberFormatInfo. string groupSep; // group separator from NumberFormatInfo. string currSymbol = null; // currency symbol from NumberFormatInfo. bool parsingCurrency = false; if ((options & NumberStyles.AllowCurrencySymbol) != 0) { currSymbol = numfmt.CurrencySymbol; // The idea here is to match the currency separators and on failure match the number separators to keep the perf of VB's IsNumeric fast. // The values of decSep are setup to use the correct relevant separator (currency in the if part and decimal in the else part). decSep = numfmt.CurrencyDecimalSeparator; groupSep = numfmt.CurrencyGroupSeparator; parsingCurrency = true; } else { decSep = numfmt.NumberDecimalSeparator; groupSep = numfmt.NumberGroupSeparator; } int state = 0; char* p = str; char ch = *p; char* next; while (true) { // Eat whitespace unless we've found a sign which isn't followed by a currency symbol. // "-Kr 1231.47" is legal but "- 1231.47" is not. if (!IsWhite(ch) || (options & NumberStyles.AllowLeadingWhite) == 0 || ((state & StateSign) != 0 && ((state & StateCurrency) == 0 && numfmt.NumberNegativePattern != 2))) { if ((((options & NumberStyles.AllowLeadingSign) != 0) && (state & StateSign) == 0) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || ((next = MatchChars(p, numfmt.NegativeSign)) != null && (number.sign = true)))) { state |= StateSign; p = next - 1; } else if (ch == '(' && ((options & NumberStyles.AllowParentheses) != 0) && ((state & StateSign) == 0)) { state |= StateSign | StateParens; number.sign = true; } else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) { state |= StateCurrency; currSymbol = null; // We already found the currency symbol. There should not be more currency symbols. Set // currSymbol to NULL so that we won't search it again in the later code path. p = next - 1; } else { break; } } ch = *++p; } int digCount = 0; int digEnd = 0; while (true) { if ((ch >= '0' && ch <= '9') || (((options & NumberStyles.AllowHexSpecifier) != 0) && ((ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F')))) { state |= StateDigits; if (ch != '0' || (state & StateNonZero) != 0) { if (digCount < NumberMaxDigits) { number.digits[digCount++] = ch; if (ch != '0' || parseDecimal) { digEnd = digCount; } } if ((state & StateDecimal) == 0) { number.scale++; } state |= StateNonZero; } else if ((state & StateDecimal) != 0) { number.scale--; } } else if (((options & NumberStyles.AllowDecimalPoint) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, decSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberDecimalSeparator)) != null)) { state |= StateDecimal; p = next - 1; } else if (((options & NumberStyles.AllowThousands) != 0) && ((state & StateDigits) != 0) && ((state & StateDecimal) == 0) && ((next = MatchChars(p, groupSep)) != null || ((parsingCurrency) && (state & StateCurrency) == 0) && (next = MatchChars(p, numfmt.NumberGroupSeparator)) != null)) { p = next - 1; } else { break; } ch = *++p; } bool negExp = false; number.precision = digEnd; number.digits[digEnd] = '\0'; if ((state & StateDigits) != 0) { if ((ch == 'E' || ch == 'e') && ((options & NumberStyles.AllowExponent) != 0)) { char* temp = p; ch = *++p; if ((next = MatchChars(p, numfmt.positiveSign)) != null) { ch = *(p = next); } else if ((next = MatchChars(p, numfmt.negativeSign)) != null) { ch = *(p = next); negExp = true; } if (ch >= '0' && ch <= '9') { int exp = 0; do { exp = exp * 10 + (ch - '0'); ch = *++p; if (exp > 1000) { exp = 9999; while (ch >= '0' && ch <= '9') { ch = *++p; } } } while (ch >= '0' && ch <= '9'); if (negExp) { exp = -exp; } number.scale += exp; } else { p = temp; ch = *p; } } while (true) { if (!IsWhite(ch) || (options & NumberStyles.AllowTrailingWhite) == 0) { if (((options & NumberStyles.AllowTrailingSign) != 0 && ((state & StateSign) == 0)) && ((next = MatchChars(p, numfmt.PositiveSign)) != null || (((next = MatchChars(p, numfmt.NegativeSign)) != null) && (number.sign = true)))) { state |= StateSign; p = next - 1; } else if (ch == ')' && ((state & StateParens) != 0)) { state &= ~StateParens; } else if (currSymbol != null && (next = MatchChars(p, currSymbol)) != null) { currSymbol = null; p = next - 1; } else { break; } } ch = *++p; } if ((state & StateParens) == 0) { if ((state & StateNonZero) == 0) { if (!parseDecimal) { number.scale = 0; } if ((state & StateDecimal) == 0) { number.sign = false; } } str = p; return true; } } str = p; return false; } internal static unsafe bool TryParseInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out int result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(s, style, ref number, info, false)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToInt32(ref number, ref result)) { return false; } } else { if (!NumberToInt32(ref number, ref result)) { return false; } } return true; } internal static unsafe bool TryParseInt64(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out long result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(s, style, ref number, info, false)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToInt64(ref number, ref result)) { return false; } } else { if (!NumberToInt64(ref number, ref result)) { return false; } } return true; } internal static unsafe bool TryParseUInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out uint result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(s, style, ref number, info, false)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToUInt32(ref number, ref result)) { return false; } } else { if (!NumberToUInt32(ref number, ref result)) { return false; } } return true; } internal static unsafe bool TryParseUInt64(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out ulong result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(s, style, ref number, info, false)) { return false; } if ((style & NumberStyles.AllowHexSpecifier) != 0) { if (!HexNumberToUInt64(ref number, ref result)) { return false; } } else { if (!NumberToUInt64(ref number, ref result)) { return false; } } return true; } internal static unsafe decimal ParseDecimal(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; decimal result = 0; StringToNumber(value, options, ref number, numfmt, true); if (!NumberBufferToDecimal(ref number, ref result)) { throw new OverflowException(SR.Overflow_Decimal); } return result; } internal static unsafe double ParseDouble(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; double d = 0; if (!TryStringToNumber(value, options, ref number, numfmt, false)) { //If we failed TryStringToNumber, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. ReadOnlySpan<char> sTrim = value.Trim(); if (sTrim.EqualsOrdinal(numfmt.PositiveInfinitySymbol)) { return double.PositiveInfinity; } if (sTrim.EqualsOrdinal(numfmt.NegativeInfinitySymbol)) { return double.NegativeInfinity; } if (sTrim.EqualsOrdinal(numfmt.NaNSymbol)) { return double.NaN; } throw new FormatException(SR.Format_InvalidString); } if (!NumberBufferToDouble(ref number, ref d)) { throw new OverflowException(SR.Overflow_Double); } return d; } internal static unsafe float ParseSingle(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt) { NumberBuffer number = default; double d = 0; if (!TryStringToNumber(value, options, ref number, numfmt, false)) { //If we failed TryStringToNumber, it may be from one of our special strings. //Check the three with which we're concerned and rethrow if it's not one of //those strings. ReadOnlySpan<char> sTrim = value.Trim(); if (sTrim.EqualsOrdinal(numfmt.PositiveInfinitySymbol)) { return float.PositiveInfinity; } if (sTrim.EqualsOrdinal(numfmt.NegativeInfinitySymbol)) { return float.NegativeInfinity; } if (sTrim.EqualsOrdinal(numfmt.NaNSymbol)) { return float.NaN; } throw new FormatException(SR.Format_InvalidString); } if (!NumberBufferToDouble(ref number, ref d)) { throw new OverflowException(SR.Overflow_Single); } float castSingle = (float)d; if (float.IsInfinity(castSingle)) { throw new OverflowException(SR.Overflow_Single); } return castSingle; } internal static unsafe bool TryParseDecimal(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out decimal result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(value, options, ref number, numfmt, true)) { return false; } if (!NumberBufferToDecimal(ref number, ref result)) { return false; } return true; } internal static unsafe bool TryParseDouble(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out double result) { NumberBuffer number = default; result = 0; if (!TryStringToNumber(value, options, ref number, numfmt, false)) { return false; } if (!NumberBufferToDouble(ref number, ref result)) { return false; } return true; } internal static unsafe bool TryParseSingle(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out float result) { NumberBuffer number = default; result = 0; double d = 0; if (!TryStringToNumber(value, options, ref number, numfmt, false)) { return false; } if (!NumberBufferToDouble(ref number, ref d)) { return false; } float castSingle = (float)d; if (float.IsInfinity(castSingle)) { return false; } result = castSingle; return true; } private static unsafe void StringToNumber(ReadOnlySpan<char> str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, bool parseDecimal) { Debug.Assert(info != null); fixed (char* stringPointer = &MemoryMarshal.GetReference(str)) { char* p = stringPointer; if (!ParseNumber(ref p, options, ref number, info, parseDecimal) || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) { throw new FormatException(SR.Format_InvalidString); } } } internal static unsafe bool TryStringToNumber(ReadOnlySpan<char> str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, bool parseDecimal) { Debug.Assert(numfmt != null); fixed (char* stringPointer = &MemoryMarshal.GetReference(str)) { char* p = stringPointer; if (!ParseNumber(ref p, options, ref number, numfmt, parseDecimal) || (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer)))) { return false; } } return true; } private static bool TrailingZeros(ReadOnlySpan<char> s, int index) { // For compatibility, we need to allow trailing zeros at the end of a number string for (int i = index; i < s.Length; i++) { if (s[i] != '\0') { return false; } } return true; } private static unsafe char* MatchChars(char* p, string str) { fixed (char* stringPointer = str) { return MatchChars(p, stringPointer); } } private static unsafe char* MatchChars(char* p, char* str) { Debug.Assert(p != null && str != null); if (*str == '\0') { return null; } // We only hurt the failure case // This fix is for French or Kazakh cultures. Since a user cannot type 0xA0 as a // space character we use 0x20 space character instead to mean the same. while (*p == *str || (*str == '\u00a0' && *p == '\u0020')) { p++; str++; if (*str == '\0') return p; } return null; } private static bool IsWhite(char ch) => ch == 0x20 || (ch >= 0x09 && ch <= 0x0D); private static bool NumberBufferToDouble(ref NumberBuffer number, ref double value) { double d = NumberToDouble(ref number); uint e = DoubleHelper.Exponent(d); ulong m = DoubleHelper.Mantissa(d); if (e == 0x7FF) { return false; } if (e == 0 && m == 0) { d = 0; } value = d; return true; } private static class DoubleHelper { public static unsafe uint Exponent(double d) => (*((uint*)&d + 1) >> 20) & 0x000007ff; public static unsafe ulong Mantissa(double d) => *((ulong*)&d) & 0x000fffffffffffff; public static unsafe bool Sign(double d) => (*((uint*)&d + 1) >> 31) != 0; } } }
namespace MyStik.TimeTable.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class ModuleCatalogV1 : DbMigration { public override void Up() { CreateTable( "dbo.StudentChannel", c => new { Id = c.Guid(nullable: false, identity: true), Label_Id = c.Guid(), Student_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.ItemLabel", t => t.Label_Id) .ForeignKey("dbo.Student", t => t.Student_Id) .Index(t => t.Label_Id) .Index(t => t.Student_Id); CreateTable( "dbo.ItemLabel", c => new { Id = c.Guid(nullable: false, identity: true), Name = c.String(), Description = c.String(), HtmlColor = c.String(), Organiser_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.ActivityOrganiser", t => t.Organiser_Id) .Index(t => t.Organiser_Id); CreateTable( "dbo.ItemLabelSet", c => new { Id = c.Guid(nullable: false, identity: true), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.CurriculumScope", c => new { Id = c.Guid(nullable: false, identity: true), IsRequired = c.Boolean(nullable: false), EarliestSection = c.Int(nullable: false), LatestSection = c.Int(nullable: false), Curriculum_Id = c.Guid(), Label_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Curriculum", t => t.Curriculum_Id) .ForeignKey("dbo.ItemLabel", t => t.Label_Id) .Index(t => t.Curriculum_Id) .Index(t => t.Label_Id); CreateTable( "dbo.CurriculumSection", c => new { Id = c.Guid(nullable: false, identity: true), Order = c.Int(nullable: false), Name = c.String(), Curriculum_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Curriculum", t => t.Curriculum_Id) .Index(t => t.Curriculum_Id); CreateTable( "dbo.CurriculumSlot", c => new { Id = c.Guid(nullable: false, identity: true), POsition = c.Int(nullable: false), Tag = c.String(), ECTS = c.Double(nullable: false), CurriculumSection_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.CurriculumSection", t => t.CurriculumSection_Id) .Index(t => t.CurriculumSection_Id); CreateTable( "dbo.TeachingModule", c => new { Id = c.Guid(nullable: false, identity: true), Name = c.String(), Description = c.String(), ECTS = c.Int(nullable: false), Semester_Id = c.Guid(), TeachingBuildingBlock_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Semester", t => t.Semester_Id) .ForeignKey("dbo.TeachingBuildingBlock", t => t.TeachingBuildingBlock_Id) .Index(t => t.Semester_Id) .Index(t => t.TeachingBuildingBlock_Id); CreateTable( "dbo.ModulePublishing", c => new { Id = c.Guid(nullable: false, identity: true), Catalog_Id = c.Guid(), Module_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.ModuleCatalog", t => t.Catalog_Id) .ForeignKey("dbo.TeachingBuildingBlock", t => t.Module_Id) .Index(t => t.Catalog_Id) .Index(t => t.Module_Id); CreateTable( "dbo.ModuleCatalog", c => new { Id = c.Guid(nullable: false, identity: true), Name = c.String(), IsPublic = c.Boolean(nullable: false), Owner_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.OrganiserMember", t => t.Owner_Id) .Index(t => t.Owner_Id); CreateTable( "dbo.TeachingAssessment", c => new { Id = c.Guid(nullable: false, identity: true), Name = c.String(), Module_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.TeachingBuildingBlock", t => t.Module_Id) .Index(t => t.Module_Id); CreateTable( "dbo.SubjectAccreditation", c => new { Id = c.Guid(nullable: false, identity: true), Semester_Id = c.Guid(), Slot_Id = c.Guid(), Subject_Id = c.Guid(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Semester", t => t.Semester_Id) .ForeignKey("dbo.CurriculumSlot", t => t.Slot_Id) .ForeignKey("dbo.TeachingUnit", t => t.Subject_Id) .Index(t => t.Semester_Id) .Index(t => t.Slot_Id) .Index(t => t.Subject_Id); CreateTable( "dbo.ItemLabelSetItemLabel", c => new { ItemLabelSet_Id = c.Guid(nullable: false), ItemLabel_Id = c.Guid(nullable: false), }) .PrimaryKey(t => new { t.ItemLabelSet_Id, t.ItemLabel_Id }) .ForeignKey("dbo.ItemLabelSet", t => t.ItemLabelSet_Id, cascadeDelete: true) .ForeignKey("dbo.ItemLabel", t => t.ItemLabel_Id, cascadeDelete: true) .Index(t => t.ItemLabelSet_Id) .Index(t => t.ItemLabel_Id); AddColumn("dbo.ExaminationUnit", "Assessment_Id", c => c.Guid()); CreateIndex("dbo.ExaminationUnit", "Assessment_Id"); AddForeignKey("dbo.ExaminationUnit", "Assessment_Id", "dbo.TeachingAssessment", "Id"); } public override void Down() { DropForeignKey("dbo.SubjectAccreditation", "Subject_Id", "dbo.TeachingUnit"); DropForeignKey("dbo.SubjectAccreditation", "Slot_Id", "dbo.CurriculumSlot"); DropForeignKey("dbo.SubjectAccreditation", "Semester_Id", "dbo.Semester"); DropForeignKey("dbo.TeachingAssessment", "Module_Id", "dbo.TeachingBuildingBlock"); DropForeignKey("dbo.ExaminationUnit", "Assessment_Id", "dbo.TeachingAssessment"); DropForeignKey("dbo.ModulePublishing", "Module_Id", "dbo.TeachingBuildingBlock"); DropForeignKey("dbo.ModulePublishing", "Catalog_Id", "dbo.ModuleCatalog"); DropForeignKey("dbo.ModuleCatalog", "Owner_Id", "dbo.OrganiserMember"); DropForeignKey("dbo.TeachingModule", "TeachingBuildingBlock_Id", "dbo.TeachingBuildingBlock"); DropForeignKey("dbo.TeachingModule", "Semester_Id", "dbo.Semester"); DropForeignKey("dbo.CurriculumSlot", "CurriculumSection_Id", "dbo.CurriculumSection"); DropForeignKey("dbo.CurriculumSection", "Curriculum_Id", "dbo.Curriculum"); DropForeignKey("dbo.CurriculumScope", "Label_Id", "dbo.ItemLabel"); DropForeignKey("dbo.CurriculumScope", "Curriculum_Id", "dbo.Curriculum"); DropForeignKey("dbo.StudentChannel", "Student_Id", "dbo.Student"); DropForeignKey("dbo.StudentChannel", "Label_Id", "dbo.ItemLabel"); DropForeignKey("dbo.ItemLabel", "Organiser_Id", "dbo.ActivityOrganiser"); DropForeignKey("dbo.ItemLabelSetItemLabel", "ItemLabel_Id", "dbo.ItemLabel"); DropForeignKey("dbo.ItemLabelSetItemLabel", "ItemLabelSet_Id", "dbo.ItemLabelSet"); DropIndex("dbo.ItemLabelSetItemLabel", new[] { "ItemLabel_Id" }); DropIndex("dbo.ItemLabelSetItemLabel", new[] { "ItemLabelSet_Id" }); DropIndex("dbo.SubjectAccreditation", new[] { "Subject_Id" }); DropIndex("dbo.SubjectAccreditation", new[] { "Slot_Id" }); DropIndex("dbo.SubjectAccreditation", new[] { "Semester_Id" }); DropIndex("dbo.ExaminationUnit", new[] { "Assessment_Id" }); DropIndex("dbo.TeachingAssessment", new[] { "Module_Id" }); DropIndex("dbo.ModuleCatalog", new[] { "Owner_Id" }); DropIndex("dbo.ModulePublishing", new[] { "Module_Id" }); DropIndex("dbo.ModulePublishing", new[] { "Catalog_Id" }); DropIndex("dbo.TeachingModule", new[] { "TeachingBuildingBlock_Id" }); DropIndex("dbo.TeachingModule", new[] { "Semester_Id" }); DropIndex("dbo.CurriculumSlot", new[] { "CurriculumSection_Id" }); DropIndex("dbo.CurriculumSection", new[] { "Curriculum_Id" }); DropIndex("dbo.CurriculumScope", new[] { "Label_Id" }); DropIndex("dbo.CurriculumScope", new[] { "Curriculum_Id" }); DropIndex("dbo.ItemLabel", new[] { "Organiser_Id" }); DropIndex("dbo.StudentChannel", new[] { "Student_Id" }); DropIndex("dbo.StudentChannel", new[] { "Label_Id" }); DropColumn("dbo.ExaminationUnit", "Assessment_Id"); DropTable("dbo.ItemLabelSetItemLabel"); DropTable("dbo.SubjectAccreditation"); DropTable("dbo.TeachingAssessment"); DropTable("dbo.ModuleCatalog"); DropTable("dbo.ModulePublishing"); DropTable("dbo.TeachingModule"); DropTable("dbo.CurriculumSlot"); DropTable("dbo.CurriculumSection"); DropTable("dbo.CurriculumScope"); DropTable("dbo.ItemLabelSet"); DropTable("dbo.ItemLabel"); DropTable("dbo.StudentChannel"); } } }
namespace KabMan.Forms { partial class VTPortDetailManagerForm { /// <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(VTPortDetailManagerForm)); this.repositoryItemLookUpEdit7 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit8 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit3 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit4 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit5 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.repositoryItemLookUpEdit2 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.CBarManager = new DevExpress.XtraBars.BarManager(this.components); this.CStatusBar = new DevExpress.XtraBars.Bar(); this.itemCount = new DevExpress.XtraBars.BarStaticItem(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.itemExit = new DevExpress.XtraBars.BarButtonItem(); this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.CGridControl = new DevExpress.XtraGrid.GridControl(); this.CGridView = new DevExpress.XtraGrid.Views.Grid.GridView(); this.CSan = new KabMan.Controls.C_LookUpControl(); this.CSanGroup = new KabMan.Controls.C_LookUpControl(); this.CCoordinate = new KabMan.Controls.C_LookUpControl(); this.CDataCenter = new KabMan.Controls.C_LookUpControl(); this.CLocation = new KabMan.Controls.C_LookUpControl(); this.CSerial = new DevExpress.XtraEditors.TextEdit(); this.CDevice = new KabMan.Controls.C_LookUpControl(); this.CBlechType = new KabMan.Controls.C_LookUpControl(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem9 = new DevExpress.XtraLayout.LayoutControlItem(); this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); this.bar2 = new DevExpress.XtraBars.Bar(); this.ItemClose = new DevExpress.XtraBars.BarButtonItem(); this.barDockControl1 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl2 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl3 = new DevExpress.XtraBars.BarDockControl(); this.barDockControl4 = new DevExpress.XtraBars.BarDockControl(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CBarManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.CGridControl)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CGridView)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CCoordinate.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSerial.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CDevice.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); this.SuspendLayout(); // // repositoryItemLookUpEdit7 // this.repositoryItemLookUpEdit7.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit7.Name = "repositoryItemLookUpEdit7"; this.repositoryItemLookUpEdit7.NullText = "Select SAN!"; // // repositoryItemLookUpEdit8 // this.repositoryItemLookUpEdit8.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit8.Name = "repositoryItemLookUpEdit8"; this.repositoryItemLookUpEdit8.NullText = "Select SAN Group!"; // // repositoryItemLookUpEdit3 // this.repositoryItemLookUpEdit3.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit3.Name = "repositoryItemLookUpEdit3"; this.repositoryItemLookUpEdit3.NullText = "Select Coordinate!"; // // repositoryItemLookUpEdit4 // this.repositoryItemLookUpEdit4.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit4.Name = "repositoryItemLookUpEdit4"; this.repositoryItemLookUpEdit4.NullText = "Select Data Center!"; // // repositoryItemLookUpEdit5 // this.repositoryItemLookUpEdit5.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.repositoryItemLookUpEdit5.Name = "repositoryItemLookUpEdit5"; this.repositoryItemLookUpEdit5.NullText = "Select Location!"; // // repositoryItemLookUpEdit1 // this.repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1"; // // repositoryItemLookUpEdit2 // this.repositoryItemLookUpEdit2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.repositoryItemLookUpEdit2.Name = "repositoryItemLookUpEdit2"; // // CBarManager // this.CBarManager.AllowCustomization = false; this.CBarManager.AllowQuickCustomization = false; this.CBarManager.AllowShowToolbarsPopup = false; this.CBarManager.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.CStatusBar}); this.CBarManager.DockControls.Add(this.barDockControlTop); this.CBarManager.DockControls.Add(this.barDockControlBottom); this.CBarManager.DockControls.Add(this.barDockControlLeft); this.CBarManager.DockControls.Add(this.barDockControlRight); this.CBarManager.Form = this; this.CBarManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.itemExit, this.itemCount}); this.CBarManager.MaxItemId = 5; this.CBarManager.StatusBar = this.CStatusBar; // // CStatusBar // this.CStatusBar.BarName = "Status Bar"; this.CStatusBar.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom; this.CStatusBar.DockCol = 0; this.CStatusBar.DockRow = 0; this.CStatusBar.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom; this.CStatusBar.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.itemCount)}); this.CStatusBar.OptionsBar.AllowQuickCustomization = false; this.CStatusBar.OptionsBar.DrawDragBorder = false; this.CStatusBar.OptionsBar.UseWholeRow = true; this.CStatusBar.Text = "Status Bar"; // // itemCount // this.itemCount.Alignment = DevExpress.XtraBars.BarItemLinkAlignment.Right; this.itemCount.Caption = "0"; this.itemCount.Id = 4; this.itemCount.Name = "itemCount"; this.itemCount.TextAlignment = System.Drawing.StringAlignment.Near; // // itemExit // this.itemExit.Caption = "Exit"; this.itemExit.Id = 3; this.itemExit.Name = "itemExit"; // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.CGridControl); this.layoutControl1.Controls.Add(this.CSan); this.layoutControl1.Controls.Add(this.CSanGroup); this.layoutControl1.Controls.Add(this.CCoordinate); this.layoutControl1.Controls.Add(this.CDataCenter); this.layoutControl1.Controls.Add(this.CLocation); this.layoutControl1.Controls.Add(this.CSerial); this.layoutControl1.Controls.Add(this.CDevice); this.layoutControl1.Controls.Add(this.CBlechType); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 26); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(530, 413); this.layoutControl1.TabIndex = 4; this.layoutControl1.Text = "layoutControl1"; // // CGridControl // this.CGridControl.Location = new System.Drawing.Point(7, 7); this.CGridControl.MainView = this.CGridView; this.CGridControl.Name = "CGridControl"; this.CGridControl.Size = new System.Drawing.Size(517, 400); this.CGridControl.TabIndex = 12; this.CGridControl.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CGridView}); // // CGridView // this.CGridView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CGridView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver; this.CGridView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray; this.CGridView.Appearance.ColumnFilterButton.Options.UseBackColor = true; this.CGridView.Appearance.ColumnFilterButton.Options.UseBorderColor = true; this.CGridView.Appearance.ColumnFilterButton.Options.UseForeColor = true; this.CGridView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CGridView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.CGridView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212))))); this.CGridView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue; this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true; this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true; this.CGridView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true; this.CGridView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.CGridView.Appearance.Empty.Options.UseBackColor = true; this.CGridView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223))))); this.CGridView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite; this.CGridView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CGridView.Appearance.EvenRow.Options.UseBackColor = true; this.CGridView.Appearance.EvenRow.Options.UseForeColor = true; this.CGridView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CGridView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225))))); this.CGridView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CGridView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CGridView.Appearance.FilterCloseButton.Options.UseBackColor = true; this.CGridView.Appearance.FilterCloseButton.Options.UseBorderColor = true; this.CGridView.Appearance.FilterCloseButton.Options.UseForeColor = true; this.CGridView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135))))); this.CGridView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CGridView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White; this.CGridView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal; this.CGridView.Appearance.FilterPanel.Options.UseBackColor = true; this.CGridView.Appearance.FilterPanel.Options.UseForeColor = true; this.CGridView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58))))); this.CGridView.Appearance.FixedLine.Options.UseBackColor = true; this.CGridView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225))))); this.CGridView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.FocusedCell.Options.UseBackColor = true; this.CGridView.Appearance.FocusedCell.Options.UseForeColor = true; this.CGridView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy; this.CGridView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178))))); this.CGridView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White; this.CGridView.Appearance.FocusedRow.Options.UseBackColor = true; this.CGridView.Appearance.FocusedRow.Options.UseForeColor = true; this.CGridView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver; this.CGridView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.FooterPanel.Options.UseBackColor = true; this.CGridView.Appearance.FooterPanel.Options.UseBorderColor = true; this.CGridView.Appearance.FooterPanel.Options.UseForeColor = true; this.CGridView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver; this.CGridView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.GroupButton.Options.UseBackColor = true; this.CGridView.Appearance.GroupButton.Options.UseBorderColor = true; this.CGridView.Appearance.GroupButton.Options.UseForeColor = true; this.CGridView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.CGridView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202))))); this.CGridView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.GroupFooter.Options.UseBackColor = true; this.CGridView.Appearance.GroupFooter.Options.UseBorderColor = true; this.CGridView.Appearance.GroupFooter.Options.UseForeColor = true; this.CGridView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165))))); this.CGridView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White; this.CGridView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.CGridView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White; this.CGridView.Appearance.GroupPanel.Options.UseBackColor = true; this.CGridView.Appearance.GroupPanel.Options.UseFont = true; this.CGridView.Appearance.GroupPanel.Options.UseForeColor = true; this.CGridView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray; this.CGridView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver; this.CGridView.Appearance.GroupRow.Options.UseBackColor = true; this.CGridView.Appearance.GroupRow.Options.UseForeColor = true; this.CGridView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver; this.CGridView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold); this.CGridView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.HeaderPanel.Options.UseBackColor = true; this.CGridView.Appearance.HeaderPanel.Options.UseBorderColor = true; this.CGridView.Appearance.HeaderPanel.Options.UseFont = true; this.CGridView.Appearance.HeaderPanel.Options.UseForeColor = true; this.CGridView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray; this.CGridView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200))))); this.CGridView.Appearance.HideSelectionRow.Options.UseBackColor = true; this.CGridView.Appearance.HideSelectionRow.Options.UseForeColor = true; this.CGridView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.HorzLine.Options.UseBackColor = true; this.CGridView.Appearance.OddRow.BackColor = System.Drawing.Color.White; this.CGridView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White; this.CGridView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal; this.CGridView.Appearance.OddRow.Options.UseBackColor = true; this.CGridView.Appearance.OddRow.Options.UseForeColor = true; this.CGridView.Appearance.Preview.BackColor = System.Drawing.Color.White; this.CGridView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy; this.CGridView.Appearance.Preview.Options.UseBackColor = true; this.CGridView.Appearance.Preview.Options.UseForeColor = true; this.CGridView.Appearance.Row.BackColor = System.Drawing.Color.White; this.CGridView.Appearance.Row.ForeColor = System.Drawing.Color.Black; this.CGridView.Appearance.Row.Options.UseBackColor = true; this.CGridView.Appearance.Row.Options.UseForeColor = true; this.CGridView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White; this.CGridView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243))))); this.CGridView.Appearance.RowSeparator.Options.UseBackColor = true; this.CGridView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138))))); this.CGridView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White; this.CGridView.Appearance.SelectedRow.Options.UseBackColor = true; this.CGridView.Appearance.SelectedRow.Options.UseForeColor = true; this.CGridView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver; this.CGridView.Appearance.VertLine.Options.UseBackColor = true; this.CGridView.GridControl = this.CGridControl; this.CGridView.Name = "CGridView"; this.CGridView.OptionsBehavior.AllowIncrementalSearch = true; this.CGridView.OptionsBehavior.Editable = false; this.CGridView.OptionsView.EnableAppearanceEvenRow = true; this.CGridView.OptionsView.EnableAppearanceOddRow = true; this.CGridView.OptionsView.ShowGroupPanel = false; this.CGridView.OptionsView.ShowIndicator = false; // // CSan // this.CSan.Columns = this.repositoryItemLookUpEdit7.Columns; this.CSan.DisplayMember = null; this.CSan.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSan.FormParameters"))); this.CSan.Location = new System.Drawing.Point(67, 59); this.CSan.Name = "CSan"; this.CSan.NullText = "Select SAN!"; this.CSan.Parameters = new KabMan.Controls.NameValuePair[0]; this.CSan.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CSan.Properties.NullText = "Select SAN!"; this.CSan.RefreshButtonVisible = true; this.CSan.Size = new System.Drawing.Size(545, 20); this.CSan.StoredProcedure = null; this.CSan.StyleController = this.layoutControl1; this.CSan.TabIndex = 11; this.CSan.TriggerControl = null; this.CSan.ValueMember = null; // // CSanGroup // this.CSanGroup.AddButtonEnabled = true; this.CSanGroup.Columns = this.repositoryItemLookUpEdit8.Columns; this.CSanGroup.DisplayMember = null; this.CSanGroup.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CSanGroup.FormParameters"))); this.CSanGroup.Location = new System.Drawing.Point(67, 28); this.CSanGroup.Name = "CSanGroup"; this.CSanGroup.NullText = "Select SAN Group!"; this.CSanGroup.Parameters = new KabMan.Controls.NameValuePair[0]; this.CSanGroup.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CSanGroup.Properties.NullText = "Select SAN Group!"; this.CSanGroup.RefreshButtonVisible = true; this.CSanGroup.Size = new System.Drawing.Size(545, 20); this.CSanGroup.StoredProcedure = null; this.CSanGroup.StyleController = this.layoutControl1; this.CSanGroup.TabIndex = 10; this.CSanGroup.TriggerControl = null; this.CSanGroup.ValueMember = null; // // CCoordinate // this.CCoordinate.Columns = this.repositoryItemLookUpEdit3.Columns; this.CCoordinate.DisplayMember = null; this.CCoordinate.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CCoordinate.FormParameters"))); this.CCoordinate.Location = new System.Drawing.Point(74, 90); this.CCoordinate.Name = "CCoordinate"; this.CCoordinate.NullText = "Select Coordinate!"; this.CCoordinate.Parameters = new KabMan.Controls.NameValuePair[0]; this.CCoordinate.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CCoordinate.Properties.NullText = "Select Coordinate!"; this.CCoordinate.RefreshButtonVisible = true; this.CCoordinate.Size = new System.Drawing.Size(538, 20); this.CCoordinate.StoredProcedure = null; this.CCoordinate.StyleController = this.layoutControl1; this.CCoordinate.TabIndex = 9; this.CCoordinate.TriggerControl = null; this.CCoordinate.ValueMember = null; // // CDataCenter // this.CDataCenter.Columns = this.repositoryItemLookUpEdit4.Columns; this.CDataCenter.DisplayMember = null; this.CDataCenter.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDataCenter.FormParameters"))); this.CDataCenter.Location = new System.Drawing.Point(74, 59); this.CDataCenter.Name = "CDataCenter"; this.CDataCenter.NullText = "Select Data Center!"; this.CDataCenter.Parameters = new KabMan.Controls.NameValuePair[0]; this.CDataCenter.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Plus, "", -1, false, true, false, DevExpress.XtraEditors.ImageLocation.MiddleCenter, null, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), "", "Add")}); this.CDataCenter.Properties.NullText = "Select Data Center!"; this.CDataCenter.RefreshButtonVisible = true; this.CDataCenter.Size = new System.Drawing.Size(538, 20); this.CDataCenter.StoredProcedure = null; this.CDataCenter.StyleController = this.layoutControl1; this.CDataCenter.TabIndex = 8; this.CDataCenter.TriggerControl = null; this.CDataCenter.ValueMember = null; // // CLocation // this.CLocation.AddButtonEnabled = true; this.CLocation.Columns = this.repositoryItemLookUpEdit5.Columns; this.CLocation.DisplayMember = null; this.CLocation.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CLocation.FormParameters"))); this.CLocation.Location = new System.Drawing.Point(74, 28); this.CLocation.Name = "CLocation"; this.CLocation.NullText = "Select Location!"; this.CLocation.Parameters = new KabMan.Controls.NameValuePair[0]; this.CLocation.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CLocation.Properties.NullText = "Select Location!"; this.CLocation.RefreshButtonVisible = true; this.CLocation.Size = new System.Drawing.Size(538, 20); this.CLocation.StoredProcedure = null; this.CLocation.StyleController = this.layoutControl1; this.CLocation.TabIndex = 7; this.CLocation.TriggerControl = null; this.CLocation.ValueMember = null; // // CSerial // this.CSerial.Location = new System.Drawing.Point(74, 90); this.CSerial.Name = "CSerial"; this.CSerial.Size = new System.Drawing.Size(538, 20); this.CSerial.StyleController = this.layoutControl1; this.CSerial.TabIndex = 6; // // CDevice // this.CDevice.AddButtonEnabled = true; this.CDevice.Columns = this.repositoryItemLookUpEdit1.Columns; this.CDevice.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CDevice.FormParameters"))); this.CDevice.Location = new System.Drawing.Point(74, 59); this.CDevice.Name = "CDevice"; this.CDevice.NullText = "Select Device to use Blech with!"; this.CDevice.Parameters = new KabMan.Controls.NameValuePair[0]; this.CDevice.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CDevice.Properties.NullText = "Select Device to use Blech with!"; this.CDevice.RefreshButtonVisible = true; this.CDevice.Size = new System.Drawing.Size(538, 20); this.CDevice.StoredProcedure = null; this.CDevice.StyleController = this.layoutControl1; this.CDevice.TabIndex = 5; this.CDevice.TriggerControl = null; // // CBlechType // this.CBlechType.AddButtonEnabled = true; this.CBlechType.Columns = this.repositoryItemLookUpEdit2.Columns; this.CBlechType.FormParameters = ((System.Collections.Generic.List<object>)(resources.GetObject("CBlechType.FormParameters"))); this.CBlechType.Location = new System.Drawing.Point(74, 28); this.CBlechType.Name = "CBlechType"; this.CBlechType.NullText = "Select Blech Type!"; this.CBlechType.Parameters = new KabMan.Controls.NameValuePair[0]; this.CBlechType.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo), new DevExpress.XtraEditors.Controls.EditorButton("Refresh", DevExpress.XtraEditors.Controls.ButtonPredefines.Redo), new DevExpress.XtraEditors.Controls.EditorButton("Add", DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)}); this.CBlechType.Properties.NullText = "Select Blech Type!"; this.CBlechType.RefreshButtonVisible = true; this.CBlechType.Size = new System.Drawing.Size(538, 20); this.CBlechType.StoredProcedure = null; this.CBlechType.StyleController = this.layoutControl1; this.CBlechType.TabIndex = 4; this.CBlechType.TriggerControl = null; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem9}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "layoutControlGroup1"; this.layoutControlGroup1.Size = new System.Drawing.Size(530, 413); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "layoutControlGroup1"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem9 // this.layoutControlItem9.Control = this.CGridControl; this.layoutControlItem9.CustomizationFormText = "layoutControlItem9"; this.layoutControlItem9.Location = new System.Drawing.Point(0, 0); this.layoutControlItem9.Name = "layoutControlItem9"; this.layoutControlItem9.Size = new System.Drawing.Size(528, 411); this.layoutControlItem9.Text = "layoutControlItem9"; this.layoutControlItem9.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem9.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem9.TextToControlDistance = 0; this.layoutControlItem9.TextVisible = false; // // barManager1 // this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { this.bar2}); this.barManager1.DockControls.Add(this.barDockControl1); this.barManager1.DockControls.Add(this.barDockControl2); this.barManager1.DockControls.Add(this.barDockControl3); this.barManager1.DockControls.Add(this.barDockControl4); this.barManager1.Form = this; this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.ItemClose}); this.barManager1.MainMenu = this.bar2; this.barManager1.MaxItemId = 1; // // bar2 // this.bar2.BarName = "Main menu"; this.bar2.DockCol = 0; this.bar2.DockRow = 0; this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; this.bar2.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(DevExpress.XtraBars.BarLinkUserDefines.PaintStyle, this.ItemClose, DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph)}); this.bar2.OptionsBar.AllowQuickCustomization = false; this.bar2.OptionsBar.DrawDragBorder = false; this.bar2.OptionsBar.UseWholeRow = true; this.bar2.Text = "Main menu"; // // ItemClose // this.ItemClose.Caption = "Exit"; this.ItemClose.Glyph = global::KabMan.Properties.Resources.ManagerExit; this.ItemClose.Id = 0; this.ItemClose.Name = "ItemClose"; this.ItemClose.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.ItemClose_ItemClick); // // VTPortDetailManagerForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(530, 464); this.Controls.Add(this.layoutControl1); this.Controls.Add(this.barDockControlLeft); this.Controls.Add(this.barDockControlRight); this.Controls.Add(this.barDockControlBottom); this.Controls.Add(this.barDockControlTop); this.Controls.Add(this.barDockControl3); this.Controls.Add(this.barDockControl4); this.Controls.Add(this.barDockControl2); this.Controls.Add(this.barDockControl1); this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(420, 500); this.Name = "VTPortDetailManagerForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "VTPort Details"; this.Load += new System.EventHandler(this.VTPortManagerForm_Load); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repositoryItemLookUpEdit2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CBarManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.CGridControl)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CGridView)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSanGroup.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CCoordinate.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CDataCenter.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CLocation.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSerial.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CDevice.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CBlechType.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem9)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraBars.BarManager CBarManager; private DevExpress.XtraBars.Bar CStatusBar; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarButtonItem itemExit; private DevExpress.XtraBars.BarStaticItem itemCount; private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraEditors.TextEdit CSerial; private KabMan.Controls.C_LookUpControl CDevice; private KabMan.Controls.C_LookUpControl CBlechType; private KabMan.Controls.C_LookUpControl CSan; private KabMan.Controls.C_LookUpControl CSanGroup; private KabMan.Controls.C_LookUpControl CCoordinate; private KabMan.Controls.C_LookUpControl CDataCenter; private KabMan.Controls.C_LookUpControl CLocation; private DevExpress.XtraGrid.GridControl CGridControl; private DevExpress.XtraGrid.Views.Grid.GridView CGridView; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem9; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit1; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit2; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit7; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit8; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit3; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit4; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit5; private DevExpress.XtraBars.BarDockControl barDockControl3; private DevExpress.XtraBars.BarDockControl barDockControl4; private DevExpress.XtraBars.BarDockControl barDockControl2; private DevExpress.XtraBars.BarDockControl barDockControl1; private DevExpress.XtraBars.BarManager barManager1; private DevExpress.XtraBars.Bar bar2; private DevExpress.XtraBars.BarButtonItem ItemClose; } }
using System; using System.IO; using SpyUO.Packets; namespace SpyUO { public class BookInfo : IComparable { private uint m_Serial; private WorldItem m_Item; private string m_Title; private string m_Author; private bool m_Writable; private string[][] m_Lines; public uint Serial{ get{ return m_Serial; } } public WorldItem Item{ get{ return m_Item; } set{ m_Item = value; } } public string Title{ get{ return m_Title; } set{ m_Title = value; } } public string Author{ get{ return m_Author; } set{ m_Author = value; } } public bool Writable{ get{ return m_Writable; } set{ m_Writable = value; } } public string[][] Lines{ get{ return m_Lines; } set{ m_Lines = value; } } public bool IsCompleted { get { for ( int i = 0; i < m_Lines.Length; i++ ) { if ( m_Lines[i] == null ) return false; } return true; } } public BookInfo( uint serial, string title, string author, bool writable, int pagesCount ) { m_Serial = serial; m_Title = title; m_Author = author; m_Writable = writable; m_Lines = new string[pagesCount][]; } public void WriteRunUOClass( StreamWriter writer ) { string baseClass; ushort itemId; uint hue; bool guess; if ( m_Item == null ) { baseClass = "BaseBook"; itemId = 0xFF2; // Blue book hue = 0; guess = true; } else { itemId = m_Item.ItemId; hue = m_Item.Hue; if ( m_Item.ItemId == 0xFF2 ) baseClass = "BlueBook"; else if ( m_Item.ItemId == 0xFEF ) baseClass = "BrownBook"; else if ( m_Item.ItemId == 0xFF1 ) baseClass = "RedBook"; else if ( m_Item.ItemId == 0xFF0 ) baseClass = "TanBook"; else baseClass = "BaseBook"; guess = false; } writer.WriteLine( "using System;" ); writer.WriteLine( "using Server;" ); writer.WriteLine(); writer.WriteLine( "namespace Server.Items" ); writer.WriteLine( "{" ); if ( guess ) writer.WriteLine( "\t// Base class, ItemID and Hue may be wrong" ); writer.WriteLine( "\tpublic class SpyUOBook : {0}", baseClass ); writer.WriteLine( "\t{" ); writer.WriteLine( "\t\tpublic static readonly BookContent Content = new BookContent" ); writer.WriteLine( "\t\t\t(" ); writer.WriteLine( "\t\t\t\t\"{0}\", \"{1}\",", Fix( m_Title ), Fix( m_Author ) ); for ( int i = 0; i < m_Lines.Length; i++ ) { if ( m_Lines[i] == null ) { writer.Write( "\t\t\t\tnew BookPageInfo()" ); if ( i + 1 < m_Lines.Length ) writer.Write( "," ); writer.WriteLine( " // Page {0} not logged", i + 1 ); } else { int linesCount = 0; for ( int j = 0; j < m_Lines[i].Length; j++ ) { if ( m_Lines[i][j].Trim() != "" ) linesCount = j + 1; } if ( linesCount == 0 ) { writer.Write( "\t\t\t\tnew BookPageInfo()" ); } else { writer.WriteLine( "\t\t\t\tnew BookPageInfo" ); writer.WriteLine( "\t\t\t\t(" ); for ( int j = 0; ; ) { writer.Write( "\t\t\t\t\t\"{0}\"", Fix( m_Lines[i][j] ) ); if ( ++j < linesCount ) { writer.WriteLine( "," ); } else { writer.WriteLine(); break; } } writer.Write( "\t\t\t\t)" ); } if ( i + 1 < m_Lines.Length ) writer.WriteLine( "," ); else writer.WriteLine(); } } writer.WriteLine( "\t\t\t);" ); writer.WriteLine(); writer.WriteLine( "\t\tpublic override BookContent DefaultContent{ get{ return Content; } }" ); writer.WriteLine(); writer.WriteLine( "\t\t[Constructable]" ); if ( baseClass != "BaseBook" ) writer.WriteLine( "\t\tpublic SpyUOBook() : base( {0} )", m_Writable ? "true" : "false" ); else writer.WriteLine( "\t\tpublic SpyUOBook() : base( 0x{0:X}, {1}, {2} )", itemId, m_Lines.Length, m_Writable ? "true" : "false" ); writer.WriteLine( "\t\t{" ); if ( hue != 0 ) { writer.WriteLine( "Hue = 0x{0:X};", hue ); writer.WriteLine(); } writer.WriteLine( "\t\t}" ); writer.WriteLine(); writer.WriteLine( "\t\tpublic SpyUOBook( Serial serial ) : base( serial )" ); writer.WriteLine( "\t\t{" ); writer.WriteLine( "\t\t}" ); writer.WriteLine(); writer.WriteLine( "\t\tpublic override void Serialize( GenericWriter writer )" ); writer.WriteLine( "\t\t{" ); writer.WriteLine( "\t\t\tbase.Serialize( writer );" ); writer.WriteLine(); writer.WriteLine( "\t\t\twriter.WriteEncodedInt( 0 ); // version" ); writer.WriteLine( "\t\t}" ); writer.WriteLine(); writer.WriteLine( "\t\tpublic override void Deserialize( GenericReader reader )" ); writer.WriteLine( "\t\t{" ); writer.WriteLine( "\t\t\tbase.Deserialize( reader );" ); writer.WriteLine(); writer.WriteLine( "\t\t\tint version = reader.ReadEncodedInt();" ); writer.WriteLine( "\t\t}" ); writer.WriteLine( "\t}" ); writer.Write( "}" ); } private static string Fix( string s ) { return s.TrimEnd().Replace( @"\", @"\\" ).Replace( "\"", "\\\"" ); } public override string ToString() { return m_Title + " - 0x" + m_Serial.ToString( "X" ) + (!IsCompleted ? " (incomplete)" : "") + (m_Item == null ? " (item not logged)" : ""); } public int CompareTo( object obj ) { BookInfo book = obj as BookInfo; if ( book == null ) return -1; else return ToString().CompareTo( book.ToString() ); } } }
// // ApplicationPkcs7MimeTests.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2022 .NET Foundation and Contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Threading.Tasks; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using NUnit.Framework; using Org.BouncyCastle.X509; using Org.BouncyCastle.Security; using Org.BouncyCastle.Crypto.Prng; using MimeKit; using MimeKit.Cryptography; using X509Certificate = Org.BouncyCastle.X509.X509Certificate; namespace UnitTests.Cryptography { [TestFixture] public abstract class ApplicationPkcs7MimeTestsBase { protected abstract SecureMimeContext CreateContext (); protected virtual EncryptionAlgorithm[] GetEncryptionAlgorithms (IDigitalSignature signature) { return ((SecureMimeDigitalSignature) signature).EncryptionAlgorithms; } [Test] public void TestArgumentExceptions () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var mailbox = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var recipients = new CmsRecipientCollection (); var signer = new CmsSigner (path, "no.secret"); var mailboxes = new [] { mailbox }; recipients.Add (new CmsRecipient (signer.Certificate)); using (var ctx = CreateContext ()) { ctx.Import (path, "no.secret"); // Compress Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Compress (null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Compress (ctx, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Compress (null)); // CompressAsync Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.CompressAsync (null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.CompressAsync (ctx, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.CompressAsync (null)); // Encrypt Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (null, mailboxes, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (null, recipients, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (ctx, (IEnumerable<MailboxAddress>) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (ctx, (CmsRecipientCollection) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (ctx, recipients, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (ctx, mailboxes, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt ((IEnumerable<MailboxAddress>) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt ((CmsRecipientCollection) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (recipients, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Encrypt (mailboxes, null)); // EncryptAsync Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (null, mailboxes, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (null, recipients, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (ctx, (IEnumerable<MailboxAddress>) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (ctx, (CmsRecipientCollection) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (ctx, recipients, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (ctx, mailboxes, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync ((IEnumerable<MailboxAddress>) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync ((CmsRecipientCollection) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (recipients, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.EncryptAsync (mailboxes, null)); // Sign Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (null, mailbox, DigestAlgorithm.Sha1, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (null, signer, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (ctx, (CmsSigner) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (ctx, mailbox, DigestAlgorithm.Sha1, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (ctx, signer, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign ((MailboxAddress) null, DigestAlgorithm.Sha1, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign ((CmsSigner) null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (mailbox, DigestAlgorithm.Sha1, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.Sign (signer, null)); // SignAsync Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (null, mailbox, DigestAlgorithm.Sha1, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (null, signer, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (ctx, (MailboxAddress) null, DigestAlgorithm.Sha1, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (ctx, (CmsSigner) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (ctx, mailbox, DigestAlgorithm.Sha1, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (ctx, signer, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync ((MailboxAddress) null, DigestAlgorithm.Sha1, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync ((CmsSigner) null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (mailbox, DigestAlgorithm.Sha1, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAsync (signer, null)); // SignAndEncrypt Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (null, mailbox, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, null, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, mailbox, DigestAlgorithm.Sha1, null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, mailbox, DigestAlgorithm.Sha1, mailboxes, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (null, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (mailbox, DigestAlgorithm.Sha1, null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (mailbox, DigestAlgorithm.Sha1, mailboxes, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (null, signer, recipients, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, null, recipients, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, signer, null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (ctx, signer, recipients, null)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (null, recipients, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (signer, null, entity)); Assert.Throws<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncrypt (signer, recipients, null)); // SignAndEncryptAsync Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (null, mailbox, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, null, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, mailbox, DigestAlgorithm.Sha1, null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, mailbox, DigestAlgorithm.Sha1, mailboxes, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (null, DigestAlgorithm.Sha1, mailboxes, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (mailbox, DigestAlgorithm.Sha1, null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (mailbox, DigestAlgorithm.Sha1, mailboxes, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (null, signer, recipients, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, null, recipients, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, signer, null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (ctx, signer, recipients, null)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (null, recipients, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (signer, null, entity)); Assert.ThrowsAsync<ArgumentNullException> (() => ApplicationPkcs7Mime.SignAndEncryptAsync (signer, recipients, null)); var compressed = ApplicationPkcs7Mime.Compress (ctx, entity); var encrypted = ApplicationPkcs7Mime.Encrypt (ctx, recipients, entity); var signed = ApplicationPkcs7Mime.Sign (ctx, signer, entity); // Decompress Assert.Throws<ArgumentNullException> (() => compressed.Decompress (null)); Assert.Throws<InvalidOperationException> (() => encrypted.Decompress ()); Assert.Throws<InvalidOperationException> (() => encrypted.Decompress (ctx)); Assert.Throws<InvalidOperationException> (() => signed.Decompress ()); Assert.Throws<InvalidOperationException> (() => signed.Decompress (ctx)); // DecompressAsync Assert.ThrowsAsync<ArgumentNullException> (() => compressed.DecompressAsync (null)); Assert.ThrowsAsync<InvalidOperationException> (() => encrypted.DecompressAsync ()); Assert.ThrowsAsync<InvalidOperationException> (() => encrypted.DecompressAsync (ctx)); Assert.ThrowsAsync<InvalidOperationException> (() => signed.DecompressAsync ()); Assert.ThrowsAsync<InvalidOperationException> (() => signed.DecompressAsync (ctx)); // Decrypt Assert.Throws<ArgumentNullException> (() => encrypted.Decrypt (null)); Assert.Throws<InvalidOperationException> (() => compressed.Decrypt (ctx)); Assert.Throws<InvalidOperationException> (() => signed.Decrypt (ctx)); // DecryptAsync Assert.ThrowsAsync<ArgumentNullException> (() => encrypted.DecryptAsync (null)); Assert.ThrowsAsync<InvalidOperationException> (() => compressed.DecryptAsync (ctx)); Assert.ThrowsAsync<InvalidOperationException> (() => signed.DecryptAsync (ctx)); // Import Assert.Throws<ArgumentNullException> (() => encrypted.Import (null)); Assert.Throws<InvalidOperationException> (() => compressed.Import (ctx)); Assert.Throws<InvalidOperationException> (() => signed.Import (ctx)); // ImportAsync Assert.ThrowsAsync<ArgumentNullException> (() => encrypted.ImportAsync (null)); Assert.ThrowsAsync<InvalidOperationException> (() => compressed.ImportAsync (ctx)); Assert.ThrowsAsync<InvalidOperationException> (() => signed.ImportAsync (ctx)); // Verify Assert.Throws<ArgumentNullException> (() => { signed.Verify (null, out _); }); Assert.Throws<InvalidOperationException> (() => { compressed.Verify (ctx, out _); }); Assert.Throws<InvalidOperationException> (() => { encrypted.Verify (ctx, out _); }); } } [Test] public void TestSecureMimeTypes () { using (var stream = new MemoryStream (Array.Empty<byte> (), false)) { ApplicationPkcs7Mime pkcs7; Assert.Throws<ArgumentOutOfRangeException> (() => new ApplicationPkcs7Mime (SecureMimeType.Unknown, stream)); pkcs7 = new ApplicationPkcs7Mime (SecureMimeType.AuthEnvelopedData, stream); Assert.AreEqual ("authenveloped-data", pkcs7.ContentType.Parameters["smime-type"]); Assert.AreEqual (SecureMimeType.AuthEnvelopedData, pkcs7.SecureMimeType); pkcs7 = new ApplicationPkcs7Mime (SecureMimeType.EnvelopedData, stream); Assert.AreEqual ("enveloped-data", pkcs7.ContentType.Parameters["smime-type"]); Assert.AreEqual (SecureMimeType.EnvelopedData, pkcs7.SecureMimeType); pkcs7 = new ApplicationPkcs7Mime (SecureMimeType.CompressedData, stream); Assert.AreEqual ("compressed-data", pkcs7.ContentType.Parameters["smime-type"]); Assert.AreEqual (SecureMimeType.CompressedData, pkcs7.SecureMimeType); pkcs7 = new ApplicationPkcs7Mime (SecureMimeType.SignedData, stream); Assert.AreEqual ("signed-data", pkcs7.ContentType.Parameters["smime-type"]); Assert.AreEqual (SecureMimeType.SignedData, pkcs7.SecureMimeType); pkcs7 = new ApplicationPkcs7Mime (SecureMimeType.CertsOnly, stream); Assert.AreEqual ("certs-only", pkcs7.ContentType.Parameters["smime-type"]); Assert.AreEqual (SecureMimeType.CertsOnly, pkcs7.SecureMimeType); pkcs7.ContentType.Parameters["smime-type"] = "x-unknown-data"; Assert.AreEqual (SecureMimeType.Unknown, pkcs7.SecureMimeType); pkcs7.ContentType.Parameters.Remove ("smime-type"); Assert.AreEqual (SecureMimeType.Unknown, pkcs7.SecureMimeType); } } void ImportAll (SecureMimeContext ctx) { var dataDir = Path.Combine (TestHelper.ProjectDir, "TestData", "smime"); string path; var chain = SecureMimeTestsBase.LoadPkcs12CertificateChain (Path.Combine (dataDir, "smime.pfx"), "no.secret"); if (ctx is WindowsSecureMimeContext windows) { var parser = new X509CertificateParser (); using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComCertificationAuthority.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.AuthRoot, certificate); } using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComClass1PrimaryIntermediateClientCA.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.CertificateAuthority, certificate); } // import the root & intermediate certificates from the smime.pfx file var store = StoreName.AuthRoot; for (int i = chain.Length - 1; i > 0; i--) { windows.Import (store, chain[i]); store = StoreName.CertificateAuthority; } } else { foreach (var filename in SecureMimeTestsBase.StartComCertificates) { path = Path.Combine (dataDir, filename); using (var stream = File.OpenRead (path)) { if (ctx is DefaultSecureMimeContext sqlite) { sqlite.Import (stream, true); } else { var parser = new X509CertificateParser (); foreach (X509Certificate certificate in parser.ReadCertificates (stream)) ctx.Import (certificate); } } } // import the root & intermediate certificates from the smime.pfx file for (int i = chain.Length - 1; i > 0; i--) { if (ctx is DefaultSecureMimeContext sqlite) { sqlite.Import (chain[i], true); } else { ctx.Import (chain[i]); } } } path = Path.Combine (dataDir, "smime.pfx"); ctx.Import (path, "no.secret"); } async Task ImportAllAsync (SecureMimeContext ctx) { var dataDir = Path.Combine (TestHelper.ProjectDir, "TestData", "smime"); string path; var chain = SecureMimeTestsBase.LoadPkcs12CertificateChain (Path.Combine (dataDir, "smime.pfx"), "no.secret"); if (ctx is WindowsSecureMimeContext windows) { var parser = new X509CertificateParser (); using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComCertificationAuthority.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.AuthRoot, certificate); } using (var stream = File.OpenRead (Path.Combine (dataDir, "StartComClass1PrimaryIntermediateClientCA.crt"))) { foreach (X509Certificate certificate in parser.ReadCertificates (stream)) windows.Import (StoreName.CertificateAuthority, certificate); } // import the root & intermediate certificates from the smime.pfx file var store = StoreName.AuthRoot; for (int i = chain.Length - 1; i > 0; i--) { windows.Import (store, chain[i]); store = StoreName.CertificateAuthority; } } else { foreach (var filename in SecureMimeTestsBase.StartComCertificates) { path = Path.Combine (dataDir, filename); using (var stream = File.OpenRead (path)) { if (ctx is DefaultSecureMimeContext sqlite) { await sqlite.ImportAsync (stream, true).ConfigureAwait (false); } else { var parser = new X509CertificateParser (); foreach (X509Certificate certificate in parser.ReadCertificates (stream)) await ctx.ImportAsync (certificate).ConfigureAwait (false); } } } // import the root & intermediate certificates from the smime.pfx file for (int i = chain.Length - 1; i > 0; i--) { if (ctx is DefaultSecureMimeContext sqlite) { await sqlite.ImportAsync (chain[i], true).ConfigureAwait (false); } else { await ctx.ImportAsync (chain[i]).ConfigureAwait (false); } } } path = Path.Combine (dataDir, "smime.pfx"); await ctx.ImportAsync (path, "no.secret").ConfigureAwait (false); } [Test] public void TestEncryptCmsRecipients () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new CmsRecipientCollection (); var signer = new CmsSigner (path, "no.secret"); recipients.Add (new CmsRecipient (signer.Certificate)); var encrypted = ApplicationPkcs7Mime.Encrypt (recipients, entity); using (var ctx = CreateContext ()) { ctx.Import (path, "no.secret"); var decrypted = encrypted.Decrypt (ctx); } } [Test] public async Task TestEncryptCmsRecipientsAsync () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new CmsRecipientCollection (); var signer = new CmsSigner (path, "no.secret"); recipients.Add (new CmsRecipient (signer.Certificate)); var encrypted = await ApplicationPkcs7Mime.EncryptAsync (recipients, entity).ConfigureAwait (false); using (var ctx = CreateContext ()) { await ctx.ImportAsync (path, "no.secret").ConfigureAwait (false); var decrypted = await encrypted.DecryptAsync (ctx).ConfigureAwait (false); } } [Test] public void TestEncryptMailboxes () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var mailbox = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var mailboxes = new[] { mailbox }; using (var ctx = CreateContext ()) { ApplicationPkcs7Mime encrypted; MimeEntity decrypted; TextPart text; ctx.Import (path, "no.secret"); encrypted = ApplicationPkcs7Mime.Encrypt (mailboxes, entity); decrypted = encrypted.Decrypt (ctx); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted from Encrypt(mailboxes, entity)"); text = (TextPart) decrypted; Assert.AreEqual (entity.Text, text.Text, "Decrypted text"); encrypted = ApplicationPkcs7Mime.Encrypt (ctx, mailboxes, entity); decrypted = encrypted.Decrypt (ctx); Assert.IsInstanceOf<TextPart> (decrypted, "Encrypt(ctx, mailboxes, entity)"); text = (TextPart) decrypted; Assert.AreEqual (entity.Text, text.Text, "Decrypted text"); } } [Test] public async Task TestEncryptMailboxesAsync () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var mailbox = new MailboxAddress ("MimeKit UnitTests", "mimekit@example.com"); var mailboxes = new[] { mailbox }; using (var ctx = CreateContext ()) { ApplicationPkcs7Mime encrypted; MimeEntity decrypted; TextPart text; await ctx.ImportAsync (path, "no.secret").ConfigureAwait (false); encrypted = await ApplicationPkcs7Mime.EncryptAsync (mailboxes, entity).ConfigureAwait (false); decrypted = await encrypted.DecryptAsync (ctx).ConfigureAwait (false); Assert.IsInstanceOf<TextPart> (decrypted, "Decrypted from EncryptAsync(mailboxes, entity)"); text = (TextPart) decrypted; Assert.AreEqual (entity.Text, text.Text, "Decrypted text"); encrypted = await ApplicationPkcs7Mime.EncryptAsync (ctx, mailboxes, entity).ConfigureAwait (false); decrypted = await encrypted.DecryptAsync (ctx).ConfigureAwait (false); Assert.IsInstanceOf<TextPart> (decrypted, "EncryptAsync(ctx, mailboxes, entity)"); text = (TextPart) decrypted; Assert.AreEqual (entity.Text, text.Text, "Decrypted text"); } } void AssertSignResults (SecureMimeContext ctx, ApplicationPkcs7Mime signed, TextPart entity) { var signatures = signed.Verify (ctx, out var encapsulated); Assert.IsInstanceOf<TextPart> (encapsulated, "TextPart"); Assert.AreEqual (entity.Text, ((TextPart) encapsulated).Text, "Text"); Assert.AreEqual (1, signatures.Count, "Signature count"); var signature = signatures[0]; Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (SecureMimeTestsBase.MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); Assert.AreEqual (SecureMimeTestsBase.MimeKitCreationDate, signature.SignerCertificate.CreationDate, "CreationDate"); Assert.AreEqual (SecureMimeTestsBase.MimeKitExpirationDate, signature.SignerCertificate.ExpirationDate, "ExpirationDate"); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.PublicKeyAlgorithm); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (SecureMimeTestsBase.UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); } [Test] public void TestSignCmsSigner () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var signer = new CmsSigner (path, "no.secret"); using (var ctx = CreateContext ()) { ImportAll (ctx); var signed = ApplicationPkcs7Mime.Sign (ctx, signer, entity); AssertSignResults (ctx, signed, entity); } } [Test] public async Task TestSignCmsSignerAsync () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var signer = new CmsSigner (path, "no.secret"); using (var ctx = CreateContext ()) { await ImportAllAsync (ctx).ConfigureAwait (false); var signed = await ApplicationPkcs7Mime.SignAsync (ctx, signer, entity).ConfigureAwait (false); AssertSignResults (ctx, signed, entity); } } [Test] public void TestSignMailbox () { var mailbox = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", SecureMimeTestsBase.MimeKitFingerprint); var entity = new TextPart ("plain") { Text = "This is some text..." }; using (var ctx = CreateContext ()) { ImportAll (ctx); var signed = ApplicationPkcs7Mime.Sign (ctx, mailbox, DigestAlgorithm.Sha224, entity); AssertSignResults (ctx, signed, entity); } } [Test] public async Task TestSignMailboxAsync () { var mailbox = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", SecureMimeTestsBase.MimeKitFingerprint); var entity = new TextPart ("plain") { Text = "This is some text..." }; using (var ctx = CreateContext ()) { await ImportAllAsync (ctx).ConfigureAwait (false); var signed = await ApplicationPkcs7Mime.SignAsync (ctx, mailbox, DigestAlgorithm.Sha224, entity).ConfigureAwait (false); AssertSignResults (ctx, signed, entity); } } void AssertSignAndEncryptResults (SecureMimeContext ctx, ApplicationPkcs7Mime encrypted, TextPart entity) { var decrypted = encrypted.Decrypt (ctx); Assert.IsInstanceOf<MultipartSigned> (decrypted, "MultipartSigned"); var signed = (MultipartSigned) decrypted; Assert.AreEqual (2, signed.Count, "MultipartSigned count"); var encapsulated = signed[0]; var signatures = signed.Verify (ctx); Assert.IsInstanceOf<TextPart> (encapsulated, "TextPart"); Assert.AreEqual (entity.Text, ((TextPart) encapsulated).Text, "Text"); Assert.AreEqual (1, signatures.Count, "Signature count"); var signature = signatures[0]; Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (SecureMimeTestsBase.MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); Assert.AreEqual (SecureMimeTestsBase.MimeKitCreationDate, signature.SignerCertificate.CreationDate, "CreationDate"); Assert.AreEqual (SecureMimeTestsBase.MimeKitExpirationDate, signature.SignerCertificate.ExpirationDate, "ExpirationDate"); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.PublicKeyAlgorithm); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (SecureMimeTestsBase.UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); } async Task AssertSignAndEncryptResultsAsync (SecureMimeContext ctx, ApplicationPkcs7Mime encrypted, TextPart entity) { var decrypted = await encrypted.DecryptAsync (ctx).ConfigureAwait (false); Assert.IsInstanceOf<MultipartSigned> (decrypted, "MultipartSigned"); var signed = (MultipartSigned) decrypted; Assert.AreEqual (2, signed.Count, "MultipartSigned count"); var encapsulated = signed[0]; var signatures = await signed.VerifyAsync (ctx).ConfigureAwait (false); Assert.IsInstanceOf<TextPart> (encapsulated, "TextPart"); Assert.AreEqual (entity.Text, ((TextPart) encapsulated).Text, "Text"); Assert.AreEqual (1, signatures.Count, "Signature count"); var signature = signatures[0]; Assert.AreEqual ("MimeKit UnitTests", signature.SignerCertificate.Name); Assert.AreEqual ("mimekit@example.com", signature.SignerCertificate.Email); Assert.AreEqual (SecureMimeTestsBase.MimeKitFingerprint, signature.SignerCertificate.Fingerprint.ToLowerInvariant ()); Assert.AreEqual (SecureMimeTestsBase.MimeKitCreationDate, signature.SignerCertificate.CreationDate, "CreationDate"); Assert.AreEqual (SecureMimeTestsBase.MimeKitExpirationDate, signature.SignerCertificate.ExpirationDate, "ExpirationDate"); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.SignerCertificate.PublicKeyAlgorithm); Assert.AreEqual (PublicKeyAlgorithm.RsaGeneral, signature.PublicKeyAlgorithm); try { bool valid = signature.Verify (); Assert.IsTrue (valid, "Bad signature from {0}", signature.SignerCertificate.Email); } catch (DigitalSignatureVerifyException ex) { if (ctx is WindowsSecureMimeContext) { // AppVeyor gets an exception about the root certificate not being trusted Assert.AreEqual (SecureMimeTestsBase.UntrustedRootCertificateMessage, ex.InnerException.Message); } else { Assert.Fail ("Failed to verify signature: {0}", ex); } } var algorithms = GetEncryptionAlgorithms (signature); int i = 0; Assert.AreEqual (EncryptionAlgorithm.Aes256, algorithms[i++], "Expected AES-256 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes192, algorithms[i++], "Expected AES-192 capability"); Assert.AreEqual (EncryptionAlgorithm.Aes128, algorithms[i++], "Expected AES-128 capability"); } [Test] public void TestSignAndEncryptCms () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new CmsRecipientCollection (); var signer = new CmsSigner (path, "no.secret"); recipients.Add (new CmsRecipient (signer.Certificate)); using (var ctx = CreateContext ()) { ImportAll (ctx); var encrypted = ApplicationPkcs7Mime.SignAndEncrypt (signer, recipients, entity); AssertSignAndEncryptResults (ctx, encrypted, entity); } } [Test] public async Task TestSignAndEncryptCmsAsync () { var path = Path.Combine (TestHelper.ProjectDir, "TestData", "smime", "smime.pfx"); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new CmsRecipientCollection (); var signer = new CmsSigner (path, "no.secret"); recipients.Add (new CmsRecipient (signer.Certificate)); using (var ctx = CreateContext ()) { await ImportAllAsync (ctx).ConfigureAwait (false); var encrypted = await ApplicationPkcs7Mime.SignAndEncryptAsync (signer, recipients, entity).ConfigureAwait (false); await AssertSignAndEncryptResultsAsync (ctx, encrypted, entity).ConfigureAwait (false); } } [Test] public void TestSignAndEncryptMailboxes () { var mailbox = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", SecureMimeTestsBase.MimeKitFingerprint); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new MailboxAddress[] { mailbox }; using (var ctx = CreateContext ()) { ImportAll (ctx); var encrypted = ApplicationPkcs7Mime.SignAndEncrypt (mailbox, DigestAlgorithm.Sha224, recipients, entity); AssertSignAndEncryptResults (ctx, encrypted, entity); } } [Test] public async Task TestSignAndEncryptMailboxesAsync () { var mailbox = new SecureMailboxAddress ("MimeKit UnitTests", "mimekit@example.com", SecureMimeTestsBase.MimeKitFingerprint); var entity = new TextPart ("plain") { Text = "This is some text..." }; var recipients = new MailboxAddress[] { mailbox }; using (var ctx = CreateContext ()) { await ImportAllAsync (ctx).ConfigureAwait (false); var encrypted = await ApplicationPkcs7Mime.SignAndEncryptAsync (mailbox, DigestAlgorithm.Sha224, recipients, entity).ConfigureAwait (false); await AssertSignAndEncryptResultsAsync (ctx, encrypted, entity).ConfigureAwait (false); } } } [TestFixture] public class ApplicationPkcs7MimeTests : ApplicationPkcs7MimeTestsBase { readonly TemporarySecureMimeContext ctx = new TemporarySecureMimeContext (new SecureRandom (new CryptoApiRandomGenerator ())) { CheckCertificateRevocation = true }; public ApplicationPkcs7MimeTests () { CryptographyContext.Register (CreateContext); } protected override SecureMimeContext CreateContext () { return ctx; } } [TestFixture] public class ApplicationPkcs7MimeSqliteTests : ApplicationPkcs7MimeTestsBase { class MySecureMimeContext : DefaultSecureMimeContext { public MySecureMimeContext () : base ("pkcs7.db", "no.secret") { CheckCertificateRevocation = true; } } public ApplicationPkcs7MimeSqliteTests () { CryptographyContext.Register (typeof (MySecureMimeContext)); } protected override SecureMimeContext CreateContext () { return new MySecureMimeContext (); } static ApplicationPkcs7MimeSqliteTests () { if (File.Exists ("pkcs7.db")) File.Delete ("pkcs7.db"); } } }
//------------------------------------------ // TorusMesh.cs (c) 2007 by Charles Petzold //------------------------------------------ using System; using System.Windows; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace Petzold.Media3D { /// <summary> /// Generates a MeshGeometry3D object for a torus. /// </summary> /// <remarks> /// The MeshGeometry3D object this class creates is available as the /// Geometry property. You can share the same instance of a TorusMesh /// object with multiple 3D visuals. In XAML files, the TorusMesh /// tag will probably appear in a resource section. /// </remarks> public class TorusMesh : MeshGeneratorBase { /// <summary> /// Initializes a new instance of the TorusMesh class. /// </summary> public TorusMesh() { PropertyChanged(new DependencyPropertyChangedEventArgs()); } /// <summary> /// Identifies the Radius dependency property. /// </summary> /// <value> /// The radius of the torus in world units. /// The default is 1. /// The Radius property can be set to a negative value, /// but in effect the torus is turned inside out so that /// the surface of the torus is colored with the BackMaterial /// brush rather than the Material brush. /// </value> public static readonly DependencyProperty RadiusProperty = DependencyProperty.Register("Radius", typeof(double), typeof(TorusMesh), new PropertyMetadata(1.0, PropertyChanged)); /// <summary> /// Gets or sets the radius of the torus. /// </summary> public double Radius { set { SetValue(RadiusProperty, value); } get { return (double)GetValue(RadiusProperty); } } /// <summary> /// Identifies the TubeRadius dependency property. /// </summary> /// <value> /// The identifier for the TubeRadius dependency property. /// </value> public static readonly DependencyProperty TubeRadiusProperty = DependencyProperty.Register("TubeRadius", typeof(double), typeof(TorusMesh), new PropertyMetadata(0.25, PropertyChanged)); /// <summary> /// Gets or sets the tube radius of the torus. /// </summary> /// <value> /// The radius of the tube that makes up the torus. /// The default is 0.25. /// </value> public double TubeRadius { set { SetValue(TubeRadiusProperty, value); } get { return (double)GetValue(TubeRadiusProperty); } } /// <summary> /// Identifies the Slices dependency property. /// </summary> public static readonly DependencyProperty SlicesProperty = DependencyProperty.Register("Slices", typeof(int), typeof(TorusMesh), new PropertyMetadata(18, PropertyChanged), ValidateSlices); // Validation callback for Slices. static bool ValidateSlices(object obj) { return (int)obj > 2; } /// <summary> /// Gets or sets the number of divisions around the torus tube. /// </summary> /// <value> /// The number of divisions around the torus tube. /// This property must be at least 3. /// The default value is 18. /// </value> /// <remarks> /// Each slice is equivalent to a number /// of degrees around the torus tube equal to 360 divided by the /// Slices value. /// </remarks> public int Slices { set { SetValue(SlicesProperty, value); } get { return (int)GetValue(SlicesProperty); } } /// <summary> /// Identifies the Stacks dependency property. /// </summary> public static readonly DependencyProperty StacksProperty = DependencyProperty.Register("Stacks", typeof(int), typeof(TorusMesh), new PropertyMetadata(36, PropertyChanged), ValidateStacks); // Validation callback for Stacks. static bool ValidateStacks(object obj) { return (int)obj > 2; } /// <summary> /// Gets or sets the number of divisions around the /// entire torus. /// </summary> /// <value> /// This property must be at least 3. /// The default value is 36. /// </value> /// <remarks> /// </remarks> public int Stacks { set { SetValue(StacksProperty, value); } get { return (int)GetValue(StacksProperty); } } /* // Static method called for any property change. static void PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { (obj as TorusMesh).PropertyChanged(args); } */ /// <summary> /// /// </summary> /// <param name="args"></param> /// <param name="vertices"></param> /// <param name="normals"></param> /// <param name="indices"></param> /// <param name="textures"></param> protected override void Triangulate(DependencyPropertyChangedEventArgs args, Point3DCollection vertices, Vector3DCollection normals, Int32Collection indices, PointCollection textures) { // Clear all four collections. vertices.Clear(); normals.Clear(); indices.Clear(); textures.Clear(); // Fill the vertices, normals, and textures collections. for (int stack = 0; stack <= Stacks; stack++) { double phi = stack * 2 * Math.PI / Stacks; double xCenter = Radius * Math.Sin(phi); double yCenter = Radius * Math.Cos(phi); Point3D pointCenter = new Point3D(xCenter, yCenter, 0); for (int slice = 0; slice <= Slices; slice++) { double theta = slice * 2 * Math.PI / Slices + Math.PI; double x = (Radius + TubeRadius * Math.Cos(theta)) * Math.Sin(phi); double y = (Radius + TubeRadius * Math.Cos(theta)) * Math.Cos(phi); double z = -TubeRadius * Math.Sin(theta); Point3D point = new Point3D(x, y, z); vertices.Add(point); normals.Add(point - pointCenter); textures.Add(new Point((double)slice / Slices, (double)stack / Stacks)); } } // Fill the indices collection. for (int stack = 0; stack < Stacks; stack++) { for (int slice = 0; slice < Slices; slice++) { indices.Add((stack + 0) * (Slices + 1) + slice); indices.Add((stack + 1) * (Slices + 1) + slice); indices.Add((stack + 0) * (Slices + 1) + slice + 1); indices.Add((stack + 0) * (Slices + 1) + slice + 1); indices.Add((stack + 1) * (Slices + 1) + slice); indices.Add((stack + 1) * (Slices + 1) + slice + 1); } } } /// <summary> /// Creates a new instance of the TorusMesh class. /// </summary> /// <returns> /// A new instance of TorusMesh. /// </returns> /// <remarks> /// Overriding this method is required when deriving /// from the Freezable class. /// </remarks> protected override Freezable CreateInstanceCore() { return new TorusMesh(); } } }
using System; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace BTDB.IL { public static class ILGenExtensions { public static IILGen Do(this IILGen il, Action<IILGen> action) { action(il); return il; } public static IILGen LdcI4(this IILGen il, int value) { switch (value) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; case -1: il.Emit(OpCodes.Ldc_I4_M1); break; default: if (value >= -128 && value <= 127) il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); else il.Emit(OpCodes.Ldc_I4, value); break; } return il; } public static IILGen LdcI8(this IILGen il, long value) { il.Emit(OpCodes.Ldc_I8, value); return il; } public static IILGen LdcR4(this IILGen il, float value) { il.Emit(OpCodes.Ldc_R4, value); return il; } public static IILGen LdcR8(this IILGen il, double value) { il.Emit(OpCodes.Ldc_R8, value); return il; } public static IILGen Ldarg(this IILGen il, ushort parameterIndex) { switch (parameterIndex) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (parameterIndex <= 255) il.Emit(OpCodes.Ldarg_S, (byte)parameterIndex); else il.Emit(OpCodes.Ldarg, parameterIndex); break; } return il; } public static IILGen Starg(this IILGen il, ushort parameterIndex) { if (parameterIndex <= 255) il.Emit(OpCodes.Starg_S, (byte)parameterIndex); else il.Emit(OpCodes.Starg, parameterIndex); return il; } public static IILGen Ldfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldfld, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldflda(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldflda, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Ldsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Ldsfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, FieldInfo fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stsfld(this IILGen il, IILField fieldInfo) { il.Emit(OpCodes.Stsfld, fieldInfo); return il; } public static IILGen Stloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Stloc_0); break; case 1: il.Emit(OpCodes.Stloc_1); break; case 2: il.Emit(OpCodes.Stloc_2); break; case 3: il.Emit(OpCodes.Stloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Stloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Stloc, localVariableIndex); break; } return il; } public static IILGen Stloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Stloc, localBuilder); return il; } public static IILGen Ldloc(this IILGen il, ushort localVariableIndex) { switch (localVariableIndex) { case 0: il.Emit(OpCodes.Ldloc_0); break; case 1: il.Emit(OpCodes.Ldloc_1); break; case 2: il.Emit(OpCodes.Ldloc_2); break; case 3: il.Emit(OpCodes.Ldloc_3); break; case 65535: throw new ArgumentOutOfRangeException(nameof(localVariableIndex)); default: if (localVariableIndex <= 255) il.Emit(OpCodes.Ldloc_S, (byte)localVariableIndex); else il.Emit(OpCodes.Ldloc, localVariableIndex); break; } return il; } public static IILGen Ldloc(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloc, localBuilder); return il; } public static IILGen Ldloca(this IILGen il, IILLocal localBuilder) { il.Emit(OpCodes.Ldloca, localBuilder); return il; } public static IILGen Constrained(this IILGen il, Type type) { il.Emit(OpCodes.Constrained, type); return il; } public static IILGen Blt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Blt, targetLabel); return il; } public static IILGen Bgt(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bgt, targetLabel); return il; } public static IILGen Brfalse(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse, targetLabel); return il; } public static IILGen BrfalseS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brfalse_S, targetLabel); return il; } public static IILGen Brtrue(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue, targetLabel); return il; } public static IILGen BrtrueS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Brtrue_S, targetLabel); return il; } public static IILGen Br(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br, targetLabel); return il; } public static IILGen BrS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Br_S, targetLabel); return il; } public static IILGen BneUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bne_Un_S, targetLabel); return il; } public static IILGen BeqS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq_S, targetLabel); return il; } public static IILGen Beq(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Beq, targetLabel); return il; } public static IILGen BgeUnS(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un_S, targetLabel); return il; } public static IILGen BgeUn(this IILGen il, IILLabel targetLabel) { il.Emit(OpCodes.Bge_Un, targetLabel); return il; } public static IILGen Newobj(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Newobj, constructorInfo); return il; } public static IILGen InitObj(this IILGen il, Type type) { il.Emit(OpCodes.Initobj, type); return il; } public static IILGen Callvirt(this IILGen il, MethodInfo methodInfo) { if (methodInfo.IsStatic) throw new ArgumentException("Method in Callvirt cannot be static"); il.Emit(OpCodes.Callvirt, methodInfo); return il; } public static IILGen Call(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Call, methodInfo); return il; } public static IILGen Call(this IILGen il, ConstructorInfo constructorInfo) { il.Emit(OpCodes.Call, constructorInfo); return il; } public static IILGen Ldftn(this IILGen il, MethodInfo methodInfo) { il.Emit(OpCodes.Ldftn, methodInfo); return il; } public static IILGen Ldnull(this IILGen il) { il.Emit(OpCodes.Ldnull); return il; } public static IILGen Throw(this IILGen il) { il.Emit(OpCodes.Throw); return il; } public static IILGen Ret(this IILGen il) { il.Emit(OpCodes.Ret); return il; } public static IILGen Pop(this IILGen il) { il.Emit(OpCodes.Pop); return il; } public static IILGen Castclass(this IILGen il, Type toType) { il.Emit(OpCodes.Castclass, toType); return il; } public static IILGen Isinst(this IILGen il, Type asType) { il.Emit(OpCodes.Isinst, asType); return il; } public static IILGen ConvU1(this IILGen il) { il.Emit(OpCodes.Conv_U1); return il; } public static IILGen ConvU2(this IILGen il) { il.Emit(OpCodes.Conv_U2); return il; } public static IILGen ConvU4(this IILGen il) { il.Emit(OpCodes.Conv_U4); return il; } public static IILGen ConvU8(this IILGen il) { il.Emit(OpCodes.Conv_U8); return il; } public static IILGen ConvI1(this IILGen il) { il.Emit(OpCodes.Conv_I1); return il; } public static IILGen ConvI2(this IILGen il) { il.Emit(OpCodes.Conv_I2); return il; } public static IILGen ConvI4(this IILGen il) { il.Emit(OpCodes.Conv_I4); return il; } public static IILGen ConvI8(this IILGen il) { il.Emit(OpCodes.Conv_I8); return il; } public static IILGen ConvR4(this IILGen il) { il.Emit(OpCodes.Conv_R4); return il; } public static IILGen ConvR8(this IILGen il) { il.Emit(OpCodes.Conv_R8); return il; } public static IILGen Tail(this IILGen il) { il.Emit(OpCodes.Tailcall); return il; } public static IILGen LdelemRef(this IILGen il) { il.Emit(OpCodes.Ldelem_Ref); return il; } public static IILGen StelemRef(this IILGen il) { il.Emit(OpCodes.Stelem_Ref); return il; } public static IILGen Ldelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Ldelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Ldelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Ldelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Ldelem_I8); else if (itemType == typeof(ushort)) il.Emit(OpCodes.Ldelem_U2); else if (itemType == typeof(byte)) il.Emit(OpCodes.Ldelem_U1); else if (itemType == typeof(uint)) il.Emit(OpCodes.Ldelem_U4); else if (itemType == typeof(float)) il.Emit(OpCodes.Ldelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Ldelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Ldelem_Ref); else il.Emit(OpCodes.Ldelem, itemType); return il; } public static IILGen Stelem(this IILGen il, Type itemType) { if (itemType == typeof(int)) il.Emit(OpCodes.Stelem_I4); else if (itemType == typeof(short)) il.Emit(OpCodes.Stelem_I2); else if (itemType == typeof(sbyte)) il.Emit(OpCodes.Stelem_I1); else if (itemType == typeof(long)) il.Emit(OpCodes.Stelem_I8); else if (itemType == typeof(float)) il.Emit(OpCodes.Stelem_R4); else if (itemType == typeof(double)) il.Emit(OpCodes.Stelem_R8); else if (!itemType.IsValueType) il.Emit(OpCodes.Stelem_Ref); else il.Emit(OpCodes.Stelem, itemType); return il; } public static IILGen Add(this IILGen il) { il.Emit(OpCodes.Add); return il; } public static IILGen Sub(this IILGen il) { il.Emit(OpCodes.Sub); return il; } public static IILGen Mul(this IILGen il) { il.Emit(OpCodes.Mul); return il; } public static IILGen Div(this IILGen il) { il.Emit(OpCodes.Div); return il; } public static IILGen Dup(this IILGen il) { il.Emit(OpCodes.Dup); return il; } public static IILGen Ldtoken(this IILGen il, Type type) { il.Emit(OpCodes.Ldtoken, type); return il; } public static IILGen Callvirt(this IILGen il, Expression<Action> expression) { var methodInfo = ((MethodCallExpression) expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Callvirt<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression newExpression) { return il.Callvirt(((PropertyInfo)newExpression.Member).GetGetMethod(true)!); } var methodInfo = ((MethodCallExpression) expression.Body).Method; return il.Callvirt(methodInfo); } public static IILGen Call(this IILGen il, Expression<Action> expression) { if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression) expression.Body).Method; return il.Call(methodInfo); } public static IILGen Call<T>(this IILGen il, Expression<Func<T>> expression) { if (expression.Body is MemberExpression memberExpression) { return il.Call(((PropertyInfo)memberExpression.Member).GetGetMethod(true)!); } if (expression.Body is NewExpression newExpression) { return il.Call(newExpression.Constructor); } var methodInfo = ((MethodCallExpression) expression.Body).Method; return il.Call(methodInfo); } public static IILGen Newobj<T>(this IILGen il, Expression<Func<T>> expression) { var constructorInfo = ((NewExpression) expression.Body).Constructor; return il.Newobj(constructorInfo); } public static IILGen Ldfld<T>(this IILGen il, Expression<Func<T>> expression) { return il.Ldfld((FieldInfo)((MemberExpression) expression.Body).Member); } public static IILGen Newarr(this IILGen il, Type arrayMemberType) { il.Emit(OpCodes.Newarr, arrayMemberType); return il; } public static IILGen Box(this IILGen il, Type boxedType) { il.Emit(OpCodes.Box, boxedType); return il; } public static IILGen Unbox(this IILGen il, Type valueType) { if (!valueType.IsValueType) throw new ArgumentException("Unboxed could be only valuetype"); il.Emit(OpCodes.Unbox, valueType); return il; } public static IILGen UnboxAny(this IILGen il, Type anyType) { il.Emit(OpCodes.Unbox_Any, anyType); return il; } public static IILGen Break(this IILGen il) { il.Emit(OpCodes.Break); return il; } public static IILGen Ld(this IILGen il, object? value) { switch (value) { case null: il.Ldnull(); break; case bool b when !b: il.LdcI4(0); break; case bool b when b: il.LdcI4(1); break; case Int16 i16: il.LdcI4(i16); // there is no instruction for 16b int break; case Int32 i32: il.LdcI4(i32); break; case Int64 i64: il.LdcI8(i64); break; case Single f: il.LdcR4(f); break; case Double d: il.LdcR8(d); break; case String s: il.Ldstr(s); break; default: throw new ArgumentException($"{value} is not supported.", nameof(value)); } return il; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text.RegularExpressions; using System.Text; using System.Threading; using Microsoft.Build.Framework; using Microsoft.Build.BuildEngine.Shared; namespace Microsoft.Build.BuildEngine { /// <summary> /// Enumeration of the results of target dependency analysis. /// </summary> /// <owner>SumedhK</owner> internal enum DependencyAnalysisResult { SkipUpToDate, SkipNoInputs, SkipNoOutputs, IncrementalBuild, FullBuild } /// <summary> /// This class is used for performing dependency analysis on targets to determine if they should be built/rebuilt/skipped. /// </summary> /// <owner>SumedhK</owner> internal sealed class TargetDependencyAnalyzer { #region Constructors /// <summary> /// Creates an instance of this class for the given target. /// </summary> /// <owner>SumedhK</owner> internal TargetDependencyAnalyzer(string projectDirectory, Target targetToAnalyze, EngineLoggingServices loggingServices, BuildEventContext buildEventContext) { ErrorUtilities.VerifyThrow(projectDirectory != null, "Need a project directory."); ErrorUtilities.VerifyThrow(targetToAnalyze != null, "Need a target to analyze."); ErrorUtilities.VerifyThrow(targetToAnalyze.TargetElement != null, "Need a target element."); this.projectDirectory = projectDirectory; this.targetToAnalyze = targetToAnalyze; this.targetInputsAttribute = targetToAnalyze.TargetElement.Attributes[XMakeAttributes.inputs]; this.targetOutputsAttribute = targetToAnalyze.TargetElement.Attributes[XMakeAttributes.outputs]; this.loggingService = loggingServices; this.buildEventContext = buildEventContext; } #endregion #region Properties /// <summary> /// Gets the target to perform dependency analysis on. /// </summary> /// <owner>SumedhK</owner> /// <value>Target object.</value> internal Target TargetToAnalyze { get { return targetToAnalyze; } } /// <summary> /// Gets the value of the target's "Inputs" attribute. /// </summary> /// <owner>SumedhK</owner> /// <value>Input specification string (can be empty).</value> private string TargetInputSpecification { get { if (targetInputSpecification == null) { targetInputSpecification = ((targetInputsAttribute != null) ? targetInputsAttribute.Value : String.Empty); } return targetInputSpecification; } } /// <summary> /// Gets the value of the target's "Outputs" attribute. /// </summary> /// <owner>SumedhK</owner> /// <value>Output specification string (can be empty).</value> private string TargetOutputSpecification { get { if (targetOutputSpecification == null) { targetOutputSpecification = ((targetOutputsAttribute != null) ? targetOutputsAttribute.Value : String.Empty); } return targetOutputSpecification; } } #endregion #region Methods /// <summary> /// Compares the target's inputs against its outputs to determine if the target needs to be built/rebuilt/skipped. /// </summary> /// <remarks> /// The collections of changed and up-to-date inputs returned from this method are valid IFF this method decides an /// incremental build is needed. /// </remarks> /// <owner>SumedhK</owner> /// <param name="bucket"></param> /// <param name="changedTargetInputs"></param> /// <param name="upToDateTargetInputs"></param> /// <returns> /// DependencyAnalysisResult.SkipUpToDate, if target is up-to-date; /// DependencyAnalysisResult.SkipNoInputs, if target has no inputs; /// DependencyAnalysisResult.SkipNoOutputs, if target has no outputs; /// DependencyAnalysisResult.IncrementalBuild, if only some target outputs are out-of-date; /// DependencyAnalysisResult.FullBuild, if target is out-of-date /// </returns> internal DependencyAnalysisResult PerformDependencyAnalysis ( ItemBucket bucket, out Hashtable changedTargetInputs, out Hashtable upToDateTargetInputs ) { // Clear any old dependency analysis logging details dependencyAnalysisDetail.Clear(); uniqueTargetInputs.Clear(); uniqueTargetOutputs.Clear(); ProjectErrorUtilities.VerifyThrowInvalidProject((TargetOutputSpecification.Length > 0) || (TargetInputSpecification.Length == 0), this.TargetToAnalyze.TargetElement, "TargetInputsSpecifiedWithoutOutputs", TargetToAnalyze.Name); DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; changedTargetInputs = null; upToDateTargetInputs = null; if (TargetOutputSpecification.Length == 0) { // if the target has no output specification, we always build it result = DependencyAnalysisResult.FullBuild; } else { Hashtable itemVectorsInTargetInputs; Hashtable itemVectorTransformsInTargetInputs; Hashtable discreteItemsInTargetInputs; Hashtable itemVectorsInTargetOutputs; Hashtable discreteItemsInTargetOutputs; ArrayList targetOutputItemSpecs; ParseTargetInputOutputSpecifications(bucket, out itemVectorsInTargetInputs, out itemVectorTransformsInTargetInputs, out discreteItemsInTargetInputs, out itemVectorsInTargetOutputs, out discreteItemsInTargetOutputs, out targetOutputItemSpecs); ArrayList itemVectorsReferencedInBothTargetInputsAndOutputs; ArrayList itemVectorsReferencedOnlyInTargetInputs; ArrayList itemVectorsReferencedOnlyInTargetOutputs = null; // if the target has no outputs because the output specification evaluated to empty if (targetOutputItemSpecs.Count == 0) { result = PerformDependencyAnalysisIfNoOutputs(); } // if there are no discrete output items... else if (discreteItemsInTargetOutputs.Count == 0) { // try to correlate inputs and outputs by checking: // 1) which item vectors are referenced by both input and output items // 2) which item vectors are referenced only by input items // 3) which item vectors are referenced only by output items // NOTE: two item vector transforms cannot be correlated, even if they reference the same item vector, because // depending on the transform expression, there might be no relation between the results of the transforms; as // a result, input items that are item vector transforms are treated as discrete items DiffHashtables(itemVectorsInTargetInputs, itemVectorsInTargetOutputs, out itemVectorsReferencedInBothTargetInputsAndOutputs, out itemVectorsReferencedOnlyInTargetInputs, out itemVectorsReferencedOnlyInTargetOutputs); // if there are no item vectors only referenced by output items... // NOTE: we consider output items that reference item vectors not referenced by any input item, as discrete // items, since we cannot correlate them to any input items if (itemVectorsReferencedOnlyInTargetOutputs.Count == 0) { /* * At this point, we know the following: * 1) the target has outputs * 2) the target has NO discrete outputs * * This implies: * 1) the target only references vectors (incl. transforms) in its outputs * 2) all vectors referenced in the outputs are also referenced in the inputs * 3) the referenced vectors are not empty * * We can thus conclude: the target MUST have (non-discrete) inputs * */ ErrorUtilities.VerifyThrow(itemVectorsReferencedInBothTargetInputsAndOutputs.Count > 0, "The target must have inputs."); Debug.Assert(GetItemSpecsFromItemVectors(itemVectorsInTargetInputs).Count > 0, "The target must have inputs."); result = PerformDependencyAnalysisIfDiscreteInputs(itemVectorsInTargetInputs, itemVectorTransformsInTargetInputs, discreteItemsInTargetInputs, itemVectorsReferencedOnlyInTargetInputs, targetOutputItemSpecs); if (result != DependencyAnalysisResult.FullBuild) { // once the inputs and outputs have been correlated, we can do a 1-to-1 comparison between each input // and its corresponding output, to discover which inputs have changed, and which are up-to-date... result = PerformDependencyAnalysisIfCorrelatedInputsOutputs(itemVectorsInTargetInputs, itemVectorsInTargetOutputs, itemVectorsReferencedInBothTargetInputsAndOutputs, out changedTargetInputs, out upToDateTargetInputs); } } } // if there are any discrete items in the target outputs, then we have no obvious correlation to the inputs they // depend on, since any input can contribute to a discrete output, so we compare all inputs against all outputs // NOTE: output items are considered discrete, if // 1) they do not reference any item vector // 2) they reference item vectors that are not referenced by any input item if ((discreteItemsInTargetOutputs.Count > 0) || ((itemVectorsReferencedOnlyInTargetOutputs != null) && (itemVectorsReferencedOnlyInTargetOutputs.Count > 0))) { result = PerformDependencyAnalysisIfDiscreteOutputs( itemVectorsInTargetInputs, itemVectorTransformsInTargetInputs, discreteItemsInTargetInputs, targetOutputItemSpecs); } if (result == DependencyAnalysisResult.SkipUpToDate) { loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseOutputsUpToDate", TargetToAnalyze.Name); // Log the target inputs & outputs if (!loggingService.OnlyLogCriticalEvents) { string inputs = null; string outputs = null; // Extract the unique inputs and outputs gatheres during TLDA ExtractUniqueInputsAndOutputs(out inputs, out outputs); if (inputs != null) { loggingService.LogComment(buildEventContext, MessageImportance.Low, "SkipTargetUpToDateInputs", inputs); } if (outputs != null) { loggingService.LogComment(buildEventContext, MessageImportance.Low, "SkipTargetUpToDateOutputs", outputs); } } } } LogReasonForBuildingTarget(result); return result; } /// <summary> /// Does appropriate logging to indicate why this target is being built fully or partially. /// </summary> /// <param name="result"></param> private void LogReasonForBuildingTarget(DependencyAnalysisResult result) { // Only if we are not logging just critical events should we be logging the details if (!loggingService.OnlyLogCriticalEvents) { if (result == DependencyAnalysisResult.FullBuild && this.dependencyAnalysisDetail.Count > 0) { // For the full build decision the are three possible outcomes loggingService.LogComment(buildEventContext,"BuildTargetCompletely", this.targetToAnalyze.Name); foreach (DependencyAnalysisLogDetail logDetail in this.dependencyAnalysisDetail) { string reason = GetFullBuildReason(logDetail); loggingService.LogCommentFromText(buildEventContext, MessageImportance.Low, reason); } } else if (result == DependencyAnalysisResult.IncrementalBuild) { // For the partial build decision the are three possible outcomes loggingService.LogComment(buildEventContext, MessageImportance.Normal, "BuildTargetPartially", this.targetToAnalyze.Name); foreach (DependencyAnalysisLogDetail logDetail in this.dependencyAnalysisDetail) { string reason = GetIncrementalBuildReason(logDetail); loggingService.LogCommentFromText(buildEventContext, MessageImportance.Low, reason); } } } } /// <summary> /// Returns a string indicating why a full build is occurring. /// </summary> internal static string GetFullBuildReason(DependencyAnalysisLogDetail logDetail) { string reason = null; if (logDetail.Reason == OutofdateReason.NewerInput) { // One of the inputs was newer than all of the outputs reason = ResourceUtilities.FormatResourceString("BuildTargetCompletelyInputNewer", logDetail.Input, logDetail.Output); } else if (logDetail.Reason == OutofdateReason.MissingOutput) { // One of the outputs was missing reason = ResourceUtilities.FormatResourceString("BuildTargetCompletelyOutputDoesntExist", logDetail.Output); } else if (logDetail.Reason == OutofdateReason.MissingInput) { // One of the inputs was missing reason = ResourceUtilities.FormatResourceString("BuildTargetCompletelyInputDoesntExist", logDetail.Input); } return reason; } /// <summary> /// Returns a string indicating why an incremental build is occurring. /// </summary> private static string GetIncrementalBuildReason(DependencyAnalysisLogDetail logDetail) { string reason = null; if (logDetail.Reason == OutofdateReason.NewerInput) { // One of the inputs was newer than its corresponding output reason = ResourceUtilities.FormatResourceString("BuildTargetPartiallyInputNewer", logDetail.InputItemName, logDetail.Input, logDetail.Output); } else if (logDetail.Reason == OutofdateReason.MissingOutput) { // One of the outputs was missing reason = ResourceUtilities.FormatResourceString("BuildTargetPartiallyOutputDoesntExist", logDetail.OutputItemName, logDetail.Input, logDetail.Output); } else if (logDetail.Reason == OutofdateReason.MissingInput) { // One of the inputs was missing reason = ResourceUtilities.FormatResourceString("BuildTargetPartiallyInputDoesntExist", logDetail.InputItemName, logDetail.Input, logDetail.Output); } return reason; } /// <summary> /// Extract only the unique inputs and outputs from all the inputs and outputs gathered /// during depedency analysis /// </summary> /// <param name="inputs">[out] the unique inputs</param> /// <param name="outputs">[out] the unique outputs</param> private void ExtractUniqueInputsAndOutputs(out string inputs, out string outputs) { if (this.uniqueTargetInputs.Count > 0) { StringBuilder inputsBuilder = new StringBuilder(); // Each of our inputs needs to be added to the string foreach (string input in this.uniqueTargetInputs.Keys) { inputsBuilder.Append(input); inputsBuilder.Append(";"); } // We don't want the trailing ; so remove it inputs = inputsBuilder.ToString(0, inputsBuilder.Length - 1); } else { inputs = String.Empty; } if (this.uniqueTargetOutputs.Count > 0) { StringBuilder outputsBuilder = new StringBuilder(); // Each of our outputs needs to be added to the string foreach (string output in this.uniqueTargetOutputs.Keys) { outputsBuilder.Append(output); outputsBuilder.Append(";"); } // We don't want the trailing ; so remove it outputs = outputsBuilder.ToString(0, outputsBuilder.Length - 1); } else { outputs = String.Empty; } } /// <summary> /// Parses the target's "Inputs" and "Outputs" attributes and gathers up referenced items. /// </summary> /// <param name="bucket"></param> /// <param name="itemVectorsInTargetInputs"></param> /// <param name="itemVectorTransformsInTargetInputs"></param> /// <param name="discreteItemsInTargetInputs"></param> /// <param name="itemVectorsInTargetOutputs"></param> /// <param name="discreteItemsInTargetOutputs"></param> /// <param name="targetOutputItemSpecs"></param> /// <owner>SumedhK</owner> private void ParseTargetInputOutputSpecifications ( ItemBucket bucket, out Hashtable itemVectorsInTargetInputs, out Hashtable itemVectorTransformsInTargetInputs, out Hashtable discreteItemsInTargetInputs, out Hashtable itemVectorsInTargetOutputs, out Hashtable discreteItemsInTargetOutputs, out ArrayList targetOutputItemSpecs ) { // break down the input/output specifications along the standard separator, after expanding all embedded properties // and item metadata Expander propertyAndMetadataExpander = new Expander(bucket.Expander, ExpanderOptions.ExpandPropertiesAndMetadata); List<string> targetInputs = propertyAndMetadataExpander.ExpandAllIntoStringListLeaveEscaped(TargetInputSpecification, this.targetInputsAttribute); List<string> targetOutputs = propertyAndMetadataExpander.ExpandAllIntoStringListLeaveEscaped(TargetOutputSpecification, this.targetOutputsAttribute); itemVectorTransformsInTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); // figure out which of the inputs are: // 1) item vectors // 2) item vectors with transforms // 3) "discrete" items i.e. items that do not reference item vectors SeparateItemVectorsFromDiscreteItems(this.targetInputsAttribute, targetInputs, bucket, out itemVectorsInTargetInputs, itemVectorTransformsInTargetInputs, out discreteItemsInTargetInputs); // figure out which of the outputs are: // 1) item vectors (with or without transforms) // 2) "discrete" items i.e. items that do not reference item vectors SeparateItemVectorsFromDiscreteItems(this.targetOutputsAttribute, targetOutputs, bucket, out itemVectorsInTargetOutputs, null /* don't want transforms separated */, out discreteItemsInTargetOutputs); // list out all the output item-specs targetOutputItemSpecs = GetItemSpecsFromItemVectors(itemVectorsInTargetOutputs); targetOutputItemSpecs.AddRange(discreteItemsInTargetOutputs.Values); } /// <summary> /// Determines if the target needs to be built/rebuilt/skipped if it has no outputs (because they evaluated to empty). /// </summary> /// <owner>SumedhK</owner> /// <returns>Indication of how to build the target.</returns> private DependencyAnalysisResult PerformDependencyAnalysisIfNoOutputs() { DependencyAnalysisResult result = DependencyAnalysisResult.SkipNoOutputs; // If the target has no inputs declared and the outputs evaluated to empty, do a full build. Remember that somebody // may specify Outputs="@(blah)", where the item list "blah" is actually produced by some task within this target. So // at the beginning, when we're trying to do to the dependency analysis, there's nothing in the "blah" list, but after // the target executes, there will be. if (TargetInputSpecification.Length == 0) { result = DependencyAnalysisResult.FullBuild; } // otherwise, don't build the target else { loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseNoOutputs", TargetToAnalyze.Name); // detailed reason is low importance to keep log clean loggingService.LogComment(buildEventContext, MessageImportance.Low, "SkipTargetBecauseNoOutputsDetail"); } return result; } /// <summary> /// Determines if the target needs to be built/rebuilt/skipped if it has discrete inputs. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVectorsInTargetInputs"></param> /// <param name="itemVectorTransformsInTargetInputs"></param> /// <param name="discreteItemsInTargetInputs"></param> /// <param name="itemVectorsReferencedOnlyInTargetInputs"></param> /// <param name="targetOutputItemSpecs"></param> /// <returns>Indication of how to build the target.</returns> private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteInputs ( Hashtable itemVectorsInTargetInputs, Hashtable itemVectorTransformsInTargetInputs, Hashtable discreteItemsInTargetInputs, ArrayList itemVectorsReferencedOnlyInTargetInputs, ArrayList targetOutputItemSpecs ) { DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; // list out all the discrete input item-specs... // NOTE: we treat input items that are item vector transforms, as discrete items, since we cannot correlate them to // any output item ArrayList discreteTargetInputItemSpecs = GetItemSpecsFromItemVectors(itemVectorTransformsInTargetInputs); discreteTargetInputItemSpecs.AddRange(discreteItemsInTargetInputs.Values); // we treat input items that reference item vectors not referenced by any output item, as discrete items, since we // cannot correlate them to any output item foreach (string itemVectorType in itemVectorsReferencedOnlyInTargetInputs) { discreteTargetInputItemSpecs.AddRange(GetItemSpecsFromItemVectors(itemVectorsInTargetInputs, itemVectorType)); } // if there are any discrete input items, we can treat them as "meta" inputs, because: // 1) we have already confirmed there are no discrete output items // 2) apart from the discrete input items, we can correlate all input items to all output items, since we know they // both reference the same item vectors // NOTES: // 1) a typical example of a "meta" input is when the project file itself is listed as an input -- this forces // rebuilds when the project file changes, even if no actual inputs have changed // 2) discrete input items and discrete output items are not treated symmetrically, because it is more likely that // an uncorrelated input is a "meta" input, than an uncorrelated output is a "meta" output, since outputs can // typically be built out of more than one set of inputs if (discreteTargetInputItemSpecs.Count > 0) { // if any output item is out-of-date w.r.t. any discrete input item, do a full build DependencyAnalysisLogDetail dependencyAnalysisDetailEntry; bool someOutOfDate = IsAnyOutOfDate(out dependencyAnalysisDetailEntry, projectDirectory, discreteTargetInputItemSpecs, targetOutputItemSpecs); if (someOutOfDate) { dependencyAnalysisDetail.Add(dependencyAnalysisDetailEntry); result = DependencyAnalysisResult.FullBuild; } else { RecordUniqueInputsAndOutputs(discreteTargetInputItemSpecs, targetOutputItemSpecs); } } return result; } /// <summary> /// Determines if the target needs to be built/rebuilt/skipped if its inputs and outputs can be correlated. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVectorsInTargetInputs"></param> /// <param name="itemVectorsInTargetOutputs"></param> /// <param name="itemVectorsReferencedInBothTargetInputsAndOutputs"></param> /// <param name="changedTargetInputs"></param> /// <param name="upToDateTargetInputs"></param> /// <returns>Indication of how to build the target.</returns> private DependencyAnalysisResult PerformDependencyAnalysisIfCorrelatedInputsOutputs ( Hashtable itemVectorsInTargetInputs, Hashtable itemVectorsInTargetOutputs, ArrayList itemVectorsReferencedInBothTargetInputsAndOutputs, out Hashtable changedTargetInputs, out Hashtable upToDateTargetInputs ) { DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; changedTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); upToDateTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); // indicates if an incremental build is really just a full build, because all input items have changed int numberOfInputItemVectorsWithAllChangedItems = 0; foreach (string itemVectorType in itemVectorsReferencedInBothTargetInputsAndOutputs) { Hashtable inputItemVectors = (Hashtable)itemVectorsInTargetInputs[itemVectorType]; Hashtable outputItemVectors = (Hashtable)itemVectorsInTargetOutputs[itemVectorType]; // NOTE: recall that transforms have been separated out already ErrorUtilities.VerifyThrow(inputItemVectors.Count == 1, "There should only be one item vector of a particular type in the target inputs that can be filtered."); // NOTE: this loop only makes one iteration foreach (BuildItemGroup inputItems in inputItemVectors.Values) { if (inputItems.Count > 0) { BuildItemGroup changedInputItems = new BuildItemGroup(); BuildItemGroup upToDateInputItems = new BuildItemGroup(); BuildItem[] inputItemsAssumedToBeUpToDate = inputItems.ToArray(); foreach (DictionaryEntry outputEntry in outputItemVectors) { BuildItemGroup outputItems = (BuildItemGroup)outputEntry.Value; // Get the metadata name so if it is missing we can print out a nice error message. string outputItemExpression = (string)outputEntry.Key; ErrorUtilities.VerifyThrow(inputItems.Count == outputItems.Count, "An item vector of a particular type must always contain the same number of items."); for (int i = 0; i < inputItemsAssumedToBeUpToDate.Length; i++) { // if we haven't already determined that this input item has changed if (inputItemsAssumedToBeUpToDate[i] != null) { // Check to see if the outputItem specification is null or empty, if that is the case we need to error out saying that some metadata // on one of the items used in the target output is missing. bool outputEscapedValueIsNullOrEmpty = String.IsNullOrEmpty(outputItems[i].FinalItemSpecEscaped); ProjectErrorUtilities.VerifyThrowInvalidProject(!outputEscapedValueIsNullOrEmpty, this.TargetToAnalyze.TargetElement, "TargetOutputsSpecifiedAreMissing", inputItemsAssumedToBeUpToDate[i].FinalItemSpecEscaped, outputItems[i].Name, outputItemExpression, TargetToAnalyze.Name); // check if it has changed bool outOfDate = IsOutOfDate(inputItemsAssumedToBeUpToDate[i].FinalItemSpecEscaped, outputItems[i].FinalItemSpecEscaped, inputItemsAssumedToBeUpToDate[i].Name, outputItems[i].Name); if (outOfDate) { changedInputItems.AddItem(inputItemsAssumedToBeUpToDate[i]); inputItemsAssumedToBeUpToDate[i] = null; result = DependencyAnalysisResult.IncrementalBuild; } } } if (changedInputItems.Count == inputItems.Count) { numberOfInputItemVectorsWithAllChangedItems++; break; } } if (changedInputItems.Count < inputItems.Count) { foreach (BuildItem item in inputItemsAssumedToBeUpToDate) { if (item != null) { upToDateInputItems.AddItem(item); } } } changedTargetInputs[itemVectorType] = changedInputItems; upToDateTargetInputs[itemVectorType] = upToDateInputItems; } } } ErrorUtilities.VerifyThrow(numberOfInputItemVectorsWithAllChangedItems <= itemVectorsReferencedInBothTargetInputsAndOutputs.Count, "The number of vectors containing all changed items cannot exceed the number of correlated vectors."); // if all correlated input items have changed if (numberOfInputItemVectorsWithAllChangedItems == itemVectorsReferencedInBothTargetInputsAndOutputs.Count) { ErrorUtilities.VerifyThrow(result == DependencyAnalysisResult.IncrementalBuild, "If inputs have changed, this must be an incremental build."); // then the incremental build is really a full build result = DependencyAnalysisResult.FullBuild; } return result; } /// <summary> /// Determines if the target needs to be built/rebuilt/skipped if it has discrete outputs. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVectorsInTargetInputs"></param> /// <param name="itemVectorTransformsInTargetInputs"></param> /// <param name="discreteItemsInTargetInputs"></param> /// <param name="targetOutputItemSpecs"></param> /// <returns>Indication of how to build the target.</returns> private DependencyAnalysisResult PerformDependencyAnalysisIfDiscreteOutputs ( Hashtable itemVectorsInTargetInputs, Hashtable itemVectorTransformsInTargetInputs, Hashtable discreteItemsInTargetInputs, ArrayList targetOutputItemSpecs ) { DependencyAnalysisResult result = DependencyAnalysisResult.SkipUpToDate; ArrayList targetInputItemSpecs = GetItemSpecsFromItemVectors(itemVectorsInTargetInputs); targetInputItemSpecs.AddRange(GetItemSpecsFromItemVectors(itemVectorTransformsInTargetInputs)); targetInputItemSpecs.AddRange(discreteItemsInTargetInputs.Values); // if the target has no inputs specified... if (targetInputItemSpecs.Count == 0) { // if the target did declare inputs, but the specification evaluated to nothing if (TargetInputSpecification.Length > 0) { loggingService.LogComment(buildEventContext, MessageImportance.Normal, "SkipTargetBecauseNoInputs", TargetToAnalyze.Name); // detailed reason is low importance to keep log clean loggingService.LogComment(buildEventContext, MessageImportance.Low, "SkipTargetBecauseNoInputsDetail"); // don't build the target result = DependencyAnalysisResult.SkipNoInputs; } else { // There were no inputs specified, so build completely loggingService.LogComment(buildEventContext, "BuildTargetCompletely", this.targetToAnalyze.Name); loggingService.LogComment(buildEventContext, "BuildTargetCompletelyNoInputsSpecified"); // otherwise, do a full build result = DependencyAnalysisResult.FullBuild; } } // if any input is newer than any output, do a full build else { DependencyAnalysisLogDetail dependencyAnalysisDetailEntry; bool someOutOfDate = IsAnyOutOfDate(out dependencyAnalysisDetailEntry, projectDirectory, targetInputItemSpecs, targetOutputItemSpecs); if (someOutOfDate) { dependencyAnalysisDetail.Add(dependencyAnalysisDetailEntry); result = DependencyAnalysisResult.FullBuild; } else { RecordUniqueInputsAndOutputs(targetInputItemSpecs, targetOutputItemSpecs); } } return result; } /// <summary> /// Separates item vectors from discrete items, and discards duplicates. If requested, item vector transforms are also /// separated out. The item vectors (and the transforms) are partitioned by type, since there can be more than one item /// vector of the same type. /// </summary> /// <remarks> /// The item vector collection is a Hashtable of Hashtables, where the top-level Hashtable is indexed by item type, and /// each "partition" Hashtable is indexed by the item vector itself. /// </remarks> /// <owner>SumedhK</owner> /// <param name="attributeContainingItems">The XML attribute which we're operating on here. /// The sole purpose of passing in this parameter is to be able to provide line/column number /// information in the event there's an error.</param> /// <param name="items"></param> /// <param name="bucket"></param> /// <param name="itemVectors"></param> /// <param name="itemVectorTransforms"></param> /// <param name="discreteItems"></param> private void SeparateItemVectorsFromDiscreteItems ( XmlAttribute attributeContainingItems, List<string> items, ItemBucket bucket, out Hashtable itemVectors, Hashtable itemVectorTransforms, out Hashtable discreteItems ) { itemVectors = new Hashtable(StringComparer.OrdinalIgnoreCase); discreteItems = new Hashtable(StringComparer.OrdinalIgnoreCase); foreach (string item in items) { Match itemVectorMatch; BuildItemGroup itemVectorContents = bucket.Expander.ExpandSingleItemListExpressionIntoItemsLeaveEscaped(item, attributeContainingItems, out itemVectorMatch); if (itemVectorContents != null) { Hashtable itemVectorCollection = null; if ((itemVectorTransforms == null) || (itemVectorMatch.Groups["TRANSFORM_SPECIFICATION"].Length == 0)) { itemVectorCollection = itemVectors; } else { itemVectorCollection = itemVectorTransforms; } string itemVectorType = itemVectorMatch.Groups["TYPE"].Value; Hashtable itemVectorCollectionPartition = (Hashtable)itemVectorCollection[itemVectorType]; if (itemVectorCollectionPartition == null) { itemVectorCollectionPartition = new Hashtable(StringComparer.OrdinalIgnoreCase); itemVectorCollection[itemVectorType] = itemVectorCollectionPartition; } itemVectorCollectionPartition[item] = itemVectorContents; ErrorUtilities.VerifyThrow((itemVectorTransforms == null) || (itemVectorCollection.Equals(itemVectorTransforms)) || (itemVectorCollectionPartition.Count == 1), "If transforms have been separated out, there should only be one item vector per partition."); } else { discreteItems[item] = item; } } } /// <summary> /// Retrieves the item-specs of all items in the given item vector collection. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVectors"></param> /// <returns>list of item-specs</returns> private static ArrayList GetItemSpecsFromItemVectors(Hashtable itemVectors) { ArrayList itemSpecs = new ArrayList(); foreach (string itemType in itemVectors.Keys) { itemSpecs.AddRange(GetItemSpecsFromItemVectors(itemVectors, itemType)); } return itemSpecs; } /// <summary> /// Retrieves the item-specs of all items of the specified type in the given item vector collection. /// </summary> /// <owner>SumedhK</owner> /// <param name="itemVectors"></param> /// <param name="itemType"></param> /// <returns>list of item-specs</returns> private static ArrayList GetItemSpecsFromItemVectors(Hashtable itemVectors, string itemType) { ArrayList itemSpecs = new ArrayList(); Hashtable itemVectorPartition = (Hashtable)itemVectors[itemType]; if (itemVectorPartition != null) { foreach (BuildItemGroup items in itemVectorPartition.Values) { foreach (BuildItem item in items) { // The FinalItemSpec can be empty-string in the case of an item transform. See bug // VSWhidbey 523719. if (item.FinalItemSpecEscaped.Length > 0) { itemSpecs.Add(item.FinalItemSpecEscaped); } } } } return itemSpecs; } /// <summary> /// Finds the differences in the keys between the two given hashtables. /// </summary> /// <owner>SumedhK</owner> /// <param name="h1"></param> /// <param name="h2"></param> /// <param name="commonKeys"></param> /// <param name="uniqueKeysInH1"></param> /// <param name="uniqueKeysInH2"></param> private static void DiffHashtables(Hashtable h1, Hashtable h2, out ArrayList commonKeys, out ArrayList uniqueKeysInH1, out ArrayList uniqueKeysInH2) { commonKeys = new ArrayList(); uniqueKeysInH1 = new ArrayList(); uniqueKeysInH2 = new ArrayList(); foreach (object h1Key in h1.Keys) { if (h2[h1Key] != null) { commonKeys.Add(h1Key); } else { uniqueKeysInH1.Add(h1Key); } } foreach (object h2Key in h2.Keys) { if (h1[h2Key] == null) { uniqueKeysInH2.Add(h2Key); } } } /// <summary> /// Compares the set of files/directories designated as "inputs" against the set of files/directories designated as /// "outputs", and indicates if any "output" file/directory is out-of-date w.r.t. any "input" file/directory. /// </summary> /// <remarks> /// NOTE: Internal for unit test purposes only. /// </remarks> /// <owner>danmose</owner> /// <param name="inputs"></param> /// <param name="outputs"></param> /// <returns>true, if any "input" is newer than any "output", or if any input or output does not exist.</returns> internal static bool IsAnyOutOfDate(out DependencyAnalysisLogDetail dependencyAnalysisDetailEntry, string projectDirectory, IList inputs, IList outputs) { ErrorUtilities.VerifyThrow((inputs.Count > 0) && (outputs.Count > 0), "Need to specify inputs and outputs."); // Algorithm: walk through all the outputs to find the oldest output // walk through the inputs as far as we need to until we find one that's newer (if any) // PERF -- we could change this to ensure that we walk the shortest list first (because we walk that one entirely): // possibly the outputs list isn't actually the shortest list. However it always is the shortest // in the cases I've seen, and adding this optimization would make the code hard to read. string oldestOutput = EscapingUtilities.UnescapeAll((string)outputs[0]); FileInfo oldestOutputInfo = null; try { string oldestOutputFullPath = Path.Combine(projectDirectory, oldestOutput); oldestOutputInfo = FileUtilities.GetFileInfoNoThrow(oldestOutputFullPath); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } // Output does not exist oldestOutputInfo = null; } if (oldestOutputInfo == null) { // First output is missing: we must build the target string arbitraryInput = EscapingUtilities.UnescapeAll((string)inputs[0]); dependencyAnalysisDetailEntry = new DependencyAnalysisLogDetail(arbitraryInput, oldestOutput, null, null, OutofdateReason.MissingOutput); return true; } for (int i = 1; i < outputs.Count; i++) { string candidateOutput = EscapingUtilities.UnescapeAll((string)outputs[i]); FileInfo candidateOutputInfo = null; try { string candidateOutputFullPath = Path.Combine(projectDirectory, candidateOutput); candidateOutputInfo = FileUtilities.GetFileInfoNoThrow(candidateOutputFullPath); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } // Output does not exist candidateOutputInfo = null; } if (candidateOutputInfo == null) { // An output is missing: we must build the target string arbitraryInput = EscapingUtilities.UnescapeAll((string)inputs[0]); dependencyAnalysisDetailEntry = new DependencyAnalysisLogDetail(arbitraryInput, candidateOutput, null, null, OutofdateReason.MissingOutput); return true; } if (oldestOutputInfo.LastWriteTime > candidateOutputInfo.LastWriteTime) { // This output is older than the previous record holder oldestOutputInfo = candidateOutputInfo; oldestOutput = candidateOutput; } } // Now compare the oldest output with each input and break out if we find one newer. foreach (string input in inputs) { string unescapedInput = EscapingUtilities.UnescapeAll(input); FileInfo inputInfo = null; try { string unescapedInputFullPath = Path.Combine(projectDirectory, unescapedInput); inputInfo = FileUtilities.GetFileInfoNoThrow(unescapedInputFullPath); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } // Output does not exist inputInfo = null; } if (inputInfo == null) { // An input is missing: we must build the target dependencyAnalysisDetailEntry = new DependencyAnalysisLogDetail(unescapedInput, oldestOutput, null, null, OutofdateReason.MissingInput); return true; } else { if (inputInfo.LastWriteTime > oldestOutputInfo.LastWriteTime) { // This input is newer than the oldest output: we must build the target dependencyAnalysisDetailEntry = new DependencyAnalysisLogDetail(unescapedInput, oldestOutput, null, null, OutofdateReason.NewerInput); return true; } } } // All exist and no inputs are newer than any outputs; up to date dependencyAnalysisDetailEntry = null; return false; } /// <summary> /// Record the unique input and output files so that the "up to date" message /// can list them in the log later. /// </summary> private void RecordUniqueInputsAndOutputs(ArrayList inputs, ArrayList outputs) { // Only if we are not logging just critical events should we be gathering full details if (!loggingService.OnlyLogCriticalEvents) { foreach (string input in inputs) { if (!this.uniqueTargetInputs.ContainsKey(input)) { this.uniqueTargetInputs.Add(input, null); } } foreach (string output in outputs) { if (!this.uniqueTargetOutputs.ContainsKey(output)) { this.uniqueTargetOutputs.Add(output, null); } } } } /// <summary> /// Compares the file/directory designated as "input" against the file/directory designated as "output", and indicates if /// the "output" file/directory is out-of-date w.r.t. the "input" file/directory. /// </summary> /// <remarks> /// If the "input" does not exist on disk, we treat its disappearance as a change, and consider the "input" to be newer /// than the "output", regardless of whether the "output" itself exists. /// </remarks> /// <owner>SumedhK</owner> /// <param name="input"></param> /// <param name="output"></param> /// <param name="inputItemName"></param> /// <param name="outputItemName"></param> /// <returns>true, if "input" is newer than "output"</returns> private bool IsOutOfDate(string input, string output, string inputItemName, string outputItemName) { bool inputDoesNotExist; bool outputDoesNotExist; input = EscapingUtilities.UnescapeAll(input); output = EscapingUtilities.UnescapeAll(output); bool outOfDate = (CompareLastWriteTimes(input, output, out inputDoesNotExist, out outputDoesNotExist) == 1) || inputDoesNotExist; // Only if we are not logging just critical events should we be gathering full details if (!loggingService.OnlyLogCriticalEvents) { // Make a not of unique inputs if (!this.uniqueTargetInputs.ContainsKey(input)) { this.uniqueTargetInputs.Add(input, null); } // Make a note of unique outputs if (!this.uniqueTargetOutputs.ContainsKey(output)) { this.uniqueTargetOutputs.Add(output, null); } } RecordComparisonResults(input, output, inputItemName, outputItemName, inputDoesNotExist, outputDoesNotExist, outOfDate); return outOfDate; } /// <summary> /// Add timestamp comparison results to a list, to log them together later. /// </summary> private void RecordComparisonResults(string input, string output, string inputItemName, string outputItemName, bool inputDoesNotExist, bool outputDoesNotExist, bool outOfDate) { // Only if we are not logging just critical events should we be gathering full details if (!loggingService.OnlyLogCriticalEvents) { // Record the details of the out-of-date decision if (inputDoesNotExist) { this.dependencyAnalysisDetail.Add(new DependencyAnalysisLogDetail(input, output, inputItemName, outputItemName, OutofdateReason.MissingInput)); } else if (outputDoesNotExist) { this.dependencyAnalysisDetail.Add(new DependencyAnalysisLogDetail(input, output, inputItemName, outputItemName, OutofdateReason.MissingOutput)); } else if (outOfDate) { this.dependencyAnalysisDetail.Add(new DependencyAnalysisLogDetail(input, output, inputItemName, outputItemName, OutofdateReason.NewerInput)); } } } /// <summary> /// Compares the last-write times of the given files/directories. /// </summary> /// <remarks> /// Existing files/directories are always considered newer than non-existent ones, and two non-existent files/directories /// are considered to have the same last-write time. /// </remarks> /// <owner>SumedhK</owner> /// <param name="path1"></param> /// <param name="path2"></param> /// <param name="path1DoesNotExist">[out] indicates if the first file/directory does not exist on disk</param> /// <param name="path2DoesNotExist">[out] indicates if the second file/directory does not exist on disk</param> /// <returns> /// -1 if the first file/directory is older than the second; /// 0 if the files/directories were both last written to at the same time; /// +1 if the first file/directory is newer than the second /// </returns> private int CompareLastWriteTimes(string path1, string path2, out bool path1DoesNotExist, out bool path2DoesNotExist) { ErrorUtilities.VerifyThrow((path1 != null) && (path1.Length > 0) && (path2 != null) && (path2.Length > 0), "Need to specify paths to compare."); FileInfo path1Info = null; try { path1 = Path.Combine(projectDirectory, path1); path1Info = FileUtilities.GetFileInfoNoThrow(path1); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } path1Info = null; } FileInfo path2Info = null; try { path2 = Path.Combine(projectDirectory, path2); path2Info = FileUtilities.GetFileInfoNoThrow(path2); } catch (Exception e) { if (ExceptionHandling.NotExpectedException(e)) { throw; } path2Info = null; } path1DoesNotExist = (path1Info == null); path2DoesNotExist = (path2Info == null); if (path1DoesNotExist) { if (path2DoesNotExist) { // Neither exist return 0; } else { // Only path 2 exists return -1; } } else if (path2DoesNotExist) { // Only path 1 exists return +1; } // Both exist return DateTime.Compare(path1Info.LastWriteTime, path2Info.LastWriteTime); } #endregion // the project directory, all relative paths are // relative to here private string projectDirectory; // the target to analyze private Target targetToAnalyze; // the value of the target's "Inputs" attribute private string targetInputSpecification; // the value of the target's "Outputs" attribute private string targetOutputSpecification; // The XmlAttribute for the "Inputs" private XmlAttribute targetInputsAttribute; // The XmlAttribute for the "Outputs" private XmlAttribute targetOutputsAttribute; // Details of the dependency analysis for logging ArrayList dependencyAnalysisDetail = new ArrayList(); // The unique target inputs Hashtable uniqueTargetInputs = new Hashtable(StringComparer.OrdinalIgnoreCase); // The unique target outputs; Hashtable uniqueTargetOutputs = new Hashtable(StringComparer.OrdinalIgnoreCase); // Engine logging service which to log message to EngineLoggingServices loggingService; // Event context information where event is raised from BuildEventContext buildEventContext; } /// <summary> /// Why TLDA decided this entry was out of date /// </summary> enum OutofdateReason { MissingInput, // The input file was missing MissingOutput, // The output file was missing NewerInput // The input file was newer } /// <summary> /// A logging detail entry. Describes what TLDA decided about inputs / outputs /// </summary> class DependencyAnalysisLogDetail { private OutofdateReason reason; private string inputItemName; private string outputItemName; private string input; private string output; /// <summary> /// The reason that we are logging this entry /// </summary> internal OutofdateReason Reason { get { return reason; } } /// <summary> /// The input item name (can be null) /// </summary> public string InputItemName { get { return inputItemName; } } /// <summary> /// The output item name (can be null) /// </summary> public string OutputItemName { get { return outputItemName; } } /// <summary> /// The input file /// </summary> public string Input { get { return input; } } /// <summary> /// The output file /// </summary> public string Output { get { return output; } } /// <summary> /// Construct a log detail element /// </summary> /// <param name="input">Input file</param> /// <param name="output">Output file</param> /// <param name="inputItemName">Input item name (can be null)</param> /// <param name="outputItemName">Output item name (can be null)</param> /// <param name="reason">The reason we are logging</param> public DependencyAnalysisLogDetail(string input, string output, string inputItemName, string outputItemName, OutofdateReason reason) { this.reason = reason; this.inputItemName = inputItemName; this.outputItemName = outputItemName; this.input = input; this.output = output; } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using Cassandra.Data.Linq; using Cassandra.IntegrationTests.Linq.Structures; using Cassandra.IntegrationTests.TestBase; using NUnit.Framework; namespace Cassandra.IntegrationTests.Linq.CqlOperatorTests { public class SubstractAssign : SimulacronTest { private readonly string _tableName = "EntityWithListType_" + Randomm.RandomAlphaNum(12); /// <summary> /// Use SubtractAssign to remove values from a list, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromList_AllValues() { var (table, expectedEntities) = EntityWithListType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); var expectedEntity = singleEntity.Clone(); expectedEntity.ListType.Clear(); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(singleEntity.ListType) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, singleEntity.ListType, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove all values from a list since they are all the same value /// </summary> [Test] public void SubtractAssign_FromList_Duplicates() { var (table, expectedEntities) = EntityWithListType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); Assert.AreEqual(1, singleEntity.ListType.Count); // make sure there's only one value in the list var indexToRemove = 0; singleEntity.ListType.AddRange(new[] { singleEntity.ListType[indexToRemove], singleEntity.ListType[indexToRemove], singleEntity.ListType[indexToRemove] }); // Get single value to remove var valsToDelete = new List<int>() { singleEntity.ListType[indexToRemove] }; // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove a single value from the beginning of the list, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromList_OneValueOfMany_IndexZero() { var (table, expectedEntities) = EntityWithListType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); singleEntity.ListType.AddRange(new[] { 999, 9999, 99999, 999999 }); // Get value to remove var indexToRemove = 0; var valsToDelete = new List<int>() { singleEntity.ListType[indexToRemove] }; var expectedEntity = singleEntity.Clone(); expectedEntity.ListType.RemoveAt(indexToRemove); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove a single value from the middle of the list, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromList_OneValueOfMany_IndexNonZero() { var (table, expectedEntities) = EntityWithListType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); singleEntity.ListType.AddRange(new[] { 999, 9999, 99999, 999999 }); // Get Value to remove var indexToRemove = 2; var valsToDelete = new List<int>() { singleEntity.ListType[indexToRemove] }; var expectedEntity = singleEntity.Clone(); expectedEntity.ListType.RemoveAt(indexToRemove); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Validate that SubractAssign does not change the list when attempting to remove a value that is not contained in the list /// </summary> [Test] public void SubtractAssign_FromList_ValNotInList() { var tupleListType = EntityWithListType.GetDefaultTable(Session, _tableName); var table = tupleListType.Item1; var expectedEntities = tupleListType.Item2; var singleEntity = expectedEntities.First(); var valsToDelete = new List<int>() { 9999 }; // make sure this value is not in the list Assert.IsFalse(singleEntity.ListType.Contains(valsToDelete.First())); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Validate that SubractAssign does not change the list when an empty list of vals to delete is passed in /// </summary> [Test] public void SubtractAssign_FromList_EmptyList() { var (table, expectedEntities) = EntityWithListType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); var valsToDelete = new List<int>(); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithListType { ListType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ListType = ListType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } //////////////////////////////////////////////////////////////////////// /// Begin Array Cases //////////////////////////////////////////////////////////////////////// /// <summary> /// Use SubtractAssign to remove values from an array, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromArray_AllValues_QueryUsingCql() { var (table, expectedEntities) = EntityWithArrayType.GetDefaultTable(Session, _tableName); var singleEntity = expectedEntities.First(); var expectedEntity = singleEntity.Clone(); expectedEntity.ArrayType = new string[] { }; // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(singleEntity.ArrayType) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, singleEntity.ArrayType, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove all values from a list since they are all the same value /// </summary> [Test] public void SubtractAssign_FromArray_Duplicates() { var tupleArrayType = EntityWithArrayType.GetDefaultTable(Session, _tableName); var table = tupleArrayType.Item1; var expectedEntities = tupleArrayType.Item2; var singleEntity = expectedEntities.First(); Assert.AreEqual(1, singleEntity.ArrayType.Length); // make sure there's only one value in the list var indexToRemove = 0; singleEntity.ArrayType.ToList().AddRange(new[] { singleEntity.ArrayType[indexToRemove], singleEntity.ArrayType[indexToRemove], singleEntity.ArrayType[indexToRemove] }); // Get single value to remove var valsToDelete = new[] { singleEntity.ArrayType[indexToRemove] }; var expectedEntity = singleEntity.Clone(); expectedEntity.ArrayType = new string[] { }; // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove a single value from the beginning of the list, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromArray_OneValueOfMany_IndexZero() { var tupleArrayType = EntityWithArrayType.GetDefaultTable(Session, _tableName); var table = tupleArrayType.Item1; var expectedEntities = tupleArrayType.Item2; var singleEntity = expectedEntities.First(); var tempList = singleEntity.ArrayType.ToList(); tempList.AddRange(new[] { "999", "9999", "99999", "999999" }); singleEntity.ArrayType = tempList.ToArray(); // Get value to remove var indexToRemove = 0; string[] valsToDelete = { singleEntity.ArrayType[indexToRemove] }; var expectedEntity = singleEntity.Clone(); tempList = expectedEntity.ArrayType.ToList(); tempList.RemoveAt(indexToRemove); expectedEntity.ArrayType = tempList.ToArray(); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Use SubtractAssign to remove a single value from the middle of the list, then validate that the expected data remains in Cassandra /// </summary> [Test] public void SubtractAssign_FromArray_OneValueOfMany_IndexNonZero() { var tupleArrayType = EntityWithArrayType.GetDefaultTable(Session, _tableName); var table = tupleArrayType.Item1; var expectedEntities = tupleArrayType.Item2; var singleEntity = expectedEntities.First(); var tempList = singleEntity.ArrayType.ToList(); tempList.AddRange(new[] { "999", "9999", "99999", "999999" }); singleEntity.ArrayType = tempList.ToArray(); // Get Value to remove var indexToRemove = 2; string[] valsToDelete = { singleEntity.ArrayType[indexToRemove] }; var expectedEntity = singleEntity.Clone(); tempList = expectedEntity.ArrayType.ToList(); tempList.RemoveAt(indexToRemove); expectedEntity.ArrayType = tempList.ToArray(); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Validate that SubractAssign does not change the list when attempting to remove a value that is not contained in the list /// </summary> [Test] public void SubtractAssign_FromArray_ValNotInArray() { var tupleArrayType = EntityWithArrayType.GetDefaultTable(Session, _tableName); var table = tupleArrayType.Item1; var expectedEntities = tupleArrayType.Item2; var singleEntity = expectedEntities.First(); string[] valsToDelete = { "9999" }; // make sure this value is not in the array Assert.AreEqual(1, singleEntity.ArrayType.Length); Assert.AreNotEqual(valsToDelete[0], singleEntity.ArrayType[0]); // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } /// <summary> /// Validate that SubractAssign does not change the list when an empty list of vals to delete is passed in /// </summary> [Test] public void SubtractAssign_FromArray_EmptyArray() { var tupleArrayType = EntityWithArrayType.GetDefaultTable(Session, _tableName); var table = tupleArrayType.Item1; var expectedEntities = tupleArrayType.Item2; var singleEntity = expectedEntities.First(); string[] valsToDelete = { }; // SubstractAssign the values table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithArrayType { ArrayType = CqlOperator.SubstractAssign(valsToDelete) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET ArrayType = ArrayType - ? WHERE Id = ?", 1, valsToDelete, singleEntity.Id); } //////////////////////////////////////////////////////////////////////// /// Begin Dictionary / Map Cases //////////////////////////////////////////////////////////////////////// /// <summary> /// Attempt to use SubtractAssign to remove a single value from a dictionary that contains a single value /// Validate Error response /// </summary> [Test] public void SubtractAssign_FromDictionary_NotAllowed() { var tupleDictionaryType = EntityWithDictionaryType.GetDefaultTable(Session, _tableName); var table = tupleDictionaryType.Item1; var expectedEntities = tupleDictionaryType.Item2; var singleEntity = expectedEntities.First(); var expectedEntity = singleEntity.Clone(); expectedEntity.DictionaryType.Clear(); var dictToDelete = new Dictionary<string, string>() { { singleEntity.DictionaryType.First().Key, singleEntity.DictionaryType.First().Value }, }; // Attempt to remove the data var updateStatement = table.Where(t => t.Id == singleEntity.Id) .Select(t => new EntityWithDictionaryType { // Use incorrect substract assign overload DictionaryType = CqlOperator.SubstractAssign(dictToDelete) }).Update(); Assert.Throws<InvalidOperationException>(() => updateStatement.Execute(), "Use dedicated method to substract assign keys only for maps"); } /// <summary> /// Remove keys from map. /// /// This test creates a map with 3 keys (firstey, secondkey, lastkey) whitin an entity, and removes keys from this map, /// and check the remaining keys result /// </summary> [TestCase(2, "firstKey")] [TestCase(1, "firstKey", "secondKey")] [TestCase(0, "firstKey", "secondKey", "lastkey")] [TestCase(3, "unexistentKey", "unexistentKey2", "unexistentKey3")] [TestCase(3, new string[0])] [TestCassandraVersion(2, 1)] public void SubtractAssign_FromDictionary(int remainingKeysCount, params string[] keysToRemove) { var tupleDictionaryType = EntityWithDictionaryType.GetDefaultTable(Session, _tableName); var table = tupleDictionaryType.Item1; var newdict = new Dictionary<string, string> { { "firstKey", "firstvalue" }, { "secondKey", "secondvalue" }, { "lastkey", "lastvalue" }, }; var id = Guid.NewGuid().ToString(); var newEntity = new EntityWithDictionaryType { Id = id, DictionaryType = newdict }; table.Where(t => t.Id == newEntity.Id).Select(x => new EntityWithDictionaryType { DictionaryType = x.DictionaryType.SubstractAssign(keysToRemove) }).Update().Execute(); VerifyBoundStatement( $"UPDATE {_tableName} SET DictionaryType = DictionaryType - ? WHERE Id = ?", 1, keysToRemove, newEntity.Id); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; using Nwc.XmlRpc; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Interfaces; using OpenSim.Services.Interfaces; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class XmlRpcGroupsServicesConnectorModule : ISharedRegionModule, IGroupsServicesConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const GroupPowers m_DefaultEveryonePowers = GroupPowers.AllowSetHome | GroupPowers.Accountable | GroupPowers.JoinChat | GroupPowers.AllowVoiceChat | GroupPowers.ReceiveNotices | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; private bool m_connectorEnabled = false; private string m_groupsServerURI = string.Empty; private bool m_disableKeepAlive = false; private string m_groupReadKey = string.Empty; private string m_groupWriteKey = string.Empty; private IUserService m_userService = null; private CommunicationsManager m_commManager = null; private bool m_debugEnabled = false; private ExpiringCache<string, XmlRpcResponse> m_memoryCache; private int m_cacheTimeout = 30; // Used to track which agents are have dropped from a group chat session // Should be reset per agent, on logon // TODO: move this to Flotsam XmlRpc Service // SessionID, List<AgentID> private Dictionary<UUID, List<UUID>> m_groupsAgentsDroppedFromChatSession = new Dictionary<UUID, List<UUID>>(); private Dictionary<UUID, List<UUID>> m_groupsAgentsInvitedToChatSession = new Dictionary<UUID, List<UUID>>(); #region IRegionModuleBase Members public string Name { get { return "XmlRpcGroupsServicesConnector"; } } // this module is not intended to be replaced, but there should only be 1 of them. public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("ServicesConnectorModule", "Default") != Name)) { m_connectorEnabled = false; return; } m_log.InfoFormat("[GROUPS-CONNECTOR]: Initializing {0}", this.Name); m_groupsServerURI = groupsConfig.GetString("GroupsServerURI", groupsConfig.GetString("XmlRpcServiceURL", string.Empty)); if ((m_groupsServerURI == null) || (m_groupsServerURI == string.Empty)) { m_log.ErrorFormat("Please specify a valid URL for GroupsServerURI in OpenSim.ini, [Groups]"); m_connectorEnabled = false; return; } m_disableKeepAlive = groupsConfig.GetBoolean("XmlRpcDisableKeepAlive", false); m_groupReadKey = groupsConfig.GetString("XmlRpcServiceReadKey", string.Empty); m_groupWriteKey = groupsConfig.GetString("XmlRpcServiceWriteKey", string.Empty); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); m_cacheTimeout = groupsConfig.GetInt("GroupsCacheTimeout", 30); if (m_cacheTimeout == 0) { m_log.WarnFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Disabled."); } else { m_log.InfoFormat("[XMLRPC-GROUPS-CONNECTOR]: Groups Cache Timeout set to {0}.", m_cacheTimeout); } // If we got all the config options we need, lets start'er'up m_memoryCache = new ExpiringCache<string, XmlRpcResponse>(); m_connectorEnabled = true; } } public void Close() { m_log.InfoFormat("[GROUPS-CONNECTOR]: Closing {0}", this.Name); } public void AddRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (m_connectorEnabled) { scene.RegisterModuleInterface<IGroupsServicesConnector>(this); if (m_userService == null) { m_userService = scene.CommsManager.UserService; m_commManager = scene.CommsManager; } } } public void RemoveRegion(OpenSim.Region.Framework.Scenes.Scene scene) { if (scene.RequestModuleInterface<IGroupsServicesConnector>() == this) { scene.UnregisterModuleInterface<IGroupsServicesConnector>(this); } } public void RegionLoaded(OpenSim.Region.Framework.Scenes.Scene scene) { // TODO: May want to consider listenning for Agent Connections so we can pre-cache group info // scene.EventManager.OnNewClient += OnNewClient; } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region IGroupsServicesConnector Members /// <summary> /// Create a Group, including Everyone and Owners Role, place FounderID in both groups, select Owner as selected role, and newly created group as agent's active role. /// </summary> public UUID CreateGroup(UUID requestingAgentID, string name, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish, UUID founderID) { UUID GroupID = UUID.Random(); UUID OwnerRoleID = UUID.Random(); Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); param["Name"] = name; param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = 0; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; param["FounderID"] = founderID.ToString(); param["EveryonePowers"] = ((ulong)m_DefaultEveryonePowers).ToString(); param["OwnerRoleID"] = OwnerRoleID.ToString(); // Would this be cleaner as (GroupPowers)ulong.MaxValue; GroupPowers OwnerPowers = GroupPowers.Accountable | GroupPowers.AllowEditLand | GroupPowers.AllowFly | GroupPowers.AllowLandmark | GroupPowers.AllowRez | GroupPowers.AllowSetHome | GroupPowers.AllowVoiceChat | GroupPowers.AssignMember | GroupPowers.AssignMemberLimited | GroupPowers.ChangeActions | GroupPowers.ChangeIdentity | GroupPowers.ChangeMedia | GroupPowers.ChangeOptions | GroupPowers.CreateRole | GroupPowers.DeedObject | GroupPowers.DeleteRole | GroupPowers.Eject | GroupPowers.FindPlaces | GroupPowers.Invite | GroupPowers.JoinChat | GroupPowers.LandChangeIdentity | GroupPowers.LandDeed | GroupPowers.LandDivideJoin | GroupPowers.LandEdit | GroupPowers.LandEjectAndFreeze | GroupPowers.LandGardening | GroupPowers.LandManageAllowed | GroupPowers.LandManageBanned | GroupPowers.LandManagePasses | GroupPowers.LandOptions | GroupPowers.LandRelease | GroupPowers.LandSetSale | GroupPowers.ModerateChat | GroupPowers.ObjectManipulate | GroupPowers.ObjectSetForSale | GroupPowers.ReceiveNotices | GroupPowers.RemoveMember | GroupPowers.ReturnGroupOwned | GroupPowers.ReturnGroupSet | GroupPowers.ReturnNonGroup | GroupPowers.RoleProperties | GroupPowers.SendNotices | GroupPowers.SetLandingPoint | GroupPowers.StartProposal | GroupPowers.VoteOnProposal; param["OwnersPowers"] = ((ulong)OwnerPowers).ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.createGroup", param); if (respData.Contains("error")) { // UUID is not nullable return UUID.Zero; } return UUID.Parse((string)respData["GroupID"]); } public void UpdateGroup(UUID requestingAgentID, UUID groupID, string charter, bool showInList, UUID insigniaID, int membershipFee, bool openEnrollment, bool allowPublish, bool maturePublish) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["Charter"] = charter; param["ShowInList"] = showInList == true ? 1 : 0; param["InsigniaID"] = insigniaID.ToString(); param["MembershipFee"] = membershipFee; param["OpenEnrollment"] = openEnrollment == true ? 1 : 0; param["AllowPublish"] = allowPublish == true ? 1 : 0; param["MaturePublish"] = maturePublish == true ? 1 : 0; XmlRpcCall(requestingAgentID, "groups.updateGroup", param); } public void AddGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); param["Name"] = name; param["Description"] = description; param["Title"] = title; param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.addRoleToGroup", param); } public void RemoveGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeRoleFromGroup", param); } public void UpdateGroupRole(UUID requestingAgentID, UUID groupID, UUID roleID, string name, string description, string title, ulong powers) { Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["RoleID"] = roleID.ToString(); if (name != null) { param["Name"] = name; } if (description != null) { param["Description"] = description; } if (title != null) { param["Title"] = title; } param["Powers"] = powers.ToString(); XmlRpcCall(requestingAgentID, "groups.updateGroupRole", param); } public GroupRecord GetGroupRecord(UUID requestingAgentID, UUID GroupID, string GroupName) { Hashtable param = new Hashtable(); if (GroupID != UUID.Zero) { param["GroupID"] = GroupID.ToString(); } if ((GroupName != null) && (GroupName != string.Empty)) { param["Name"] = GroupName.ToString(); } Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { return null; } return GroupProfileHashtableToGroupRecord(respData); } public GroupProfileData GetMemberGroupProfile(UUID requestingAgentID, UUID GroupID, UUID AgentID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroup", param); if (respData.Contains("error")) { // GroupProfileData is not nullable return new GroupProfileData(); } GroupMembershipData MemberInfo = GetAgentGroupMembership(requestingAgentID, AgentID, GroupID); GroupProfileData MemberGroupProfile = GroupProfileHashtableToGroupProfileData(respData); MemberGroupProfile.MemberTitle = MemberInfo.GroupTitle; MemberGroupProfile.PowersMask = MemberInfo.GroupPowers; return MemberGroupProfile; } public void SetAgentActiveGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentActiveGroup", param); } public void SetAgentActiveGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["SelectedRoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); } public void SetAgentGroupInfo(UUID requestingAgentID, UUID AgentID, UUID GroupID, bool AcceptNotices, bool ListInProfile) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["AcceptNotices"] = AcceptNotices ? "1" : "0"; param["ListInProfile"] = ListInProfile ? "1" : "0"; XmlRpcCall(requestingAgentID, "groups.setAgentGroupInfo", param); } public void AddAgentToGroupInvite(UUID requestingAgentID, UUID inviteID, UUID groupID, UUID roleID, UUID agentID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); param["AgentID"] = agentID.ToString(); param["RoleID"] = roleID.ToString(); param["GroupID"] = groupID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupInvite", param); } public GroupInviteInfo GetAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentToGroupInvite", param); if (respData.Contains("error")) { return null; } GroupInviteInfo inviteInfo = new GroupInviteInfo(); inviteInfo.InviteID = inviteID; inviteInfo.GroupID = UUID.Parse((string)respData["GroupID"]); inviteInfo.RoleID = UUID.Parse((string)respData["RoleID"]); inviteInfo.AgentID = UUID.Parse((string)respData["AgentID"]); return inviteInfo; } public void RemoveAgentToGroupInvite(UUID requestingAgentID, UUID inviteID) { Hashtable param = new Hashtable(); param["InviteID"] = inviteID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentToGroupInvite", param); } public void AddAgentToGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroup", param); } public void RemoveAgentFromGroup(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroup", param); } public void AddAgentToGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.addAgentToGroupRole", param); } public void RemoveAgentFromGroupRole(UUID requestingAgentID, UUID AgentID, UUID GroupID, UUID RoleID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); param["RoleID"] = RoleID.ToString(); XmlRpcCall(requestingAgentID, "groups.removeAgentFromGroupRole", param); } public List<DirGroupsReplyData> FindGroups(UUID requestingAgentID, string search) { Hashtable param = new Hashtable(); param["Search"] = search; Hashtable respData = XmlRpcCall(requestingAgentID, "groups.findGroups", param); List<DirGroupsReplyData> findings = new List<DirGroupsReplyData>(); if (!respData.Contains("error")) { Hashtable results = (Hashtable)respData["results"]; foreach (Hashtable groupFind in results.Values) { DirGroupsReplyData data = new DirGroupsReplyData(); data.groupID = new UUID((string)groupFind["GroupID"]); ; data.groupName = (string)groupFind["Name"]; data.members = int.Parse((string)groupFind["Members"]); // data.searchOrder = order; findings.Add(data); } } return findings; } public GroupMembershipData GetAgentGroupMembership(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMembership", param); if (respData.Contains("error")) { return null; } GroupMembershipData data = HashTableToGroupMembershipData(respData); return data; } public GroupMembershipData GetAgentActiveMembership(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentActiveMembership", param); if (respData.Contains("error")) { return null; } return HashTableToGroupMembershipData(respData); } public List<GroupMembershipData> GetAgentGroupMemberships(UUID requestingAgentID, UUID AgentID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentGroupMemberships", param); List<GroupMembershipData> memberships = new List<GroupMembershipData>(); if (!respData.Contains("error")) { foreach (object membership in respData.Values) { memberships.Add(HashTableToGroupMembershipData((Hashtable)membership)); } } return memberships; } public List<GroupRolesData> GetAgentGroupRoles(UUID requestingAgentID, UUID AgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["AgentID"] = AgentID.ToString(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getAgentRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.RoleID = new UUID((string)role["RoleID"]); data.Name = (string)role["Name"]; data.Description = (string)role["Description"]; data.Powers = ulong.Parse((string)role["Powers"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupRolesData> GetGroupRoles(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoles", param); List<GroupRolesData> Roles = new List<GroupRolesData>(); if (respData.Contains("error")) { return Roles; } foreach (Hashtable role in respData.Values) { GroupRolesData data = new GroupRolesData(); data.Description = (string)role["Description"]; data.Members = int.Parse((string)role["Members"]); data.Name = (string)role["Name"]; data.Powers = ulong.Parse((string)role["Powers"]); data.RoleID = new UUID((string)role["RoleID"]); data.Title = (string)role["Title"]; Roles.Add(data); } return Roles; } public List<GroupMembersData> GetGroupMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupMembers", param); List<GroupMembersData> members = new List<GroupMembersData>(); if (respData.Contains("error")) { return members; } foreach (Hashtable membership in respData.Values) { GroupMembersData data = new GroupMembersData(); data.AcceptNotices = ((string)membership["AcceptNotices"]) == "1"; data.AgentID = new UUID((string)membership["AgentID"]); data.Contribution = int.Parse((string)membership["Contribution"]); data.IsOwner = ((string)membership["IsOwner"]) == "1"; data.ListInProfile = ((string)membership["ListInProfile"]) == "1"; data.AgentPowers = ulong.Parse((string)membership["AgentPowers"]); data.Title = (string)membership["Title"]; members.Add(data); } return members; } public List<GroupRoleMembersData> GetGroupRoleMembers(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupRoleMembers", param); List<GroupRoleMembersData> members = new List<GroupRoleMembersData>(); if (!respData.Contains("error")) { foreach (Hashtable membership in respData.Values) { GroupRoleMembersData data = new GroupRoleMembersData(); data.MemberID = new UUID((string)membership["AgentID"]); data.RoleID = new UUID((string)membership["RoleID"]); members.Add(data); } } return members; } public List<GroupNoticeData> GetGroupNotices(UUID requestingAgentID, UUID GroupID) { Hashtable param = new Hashtable(); param["GroupID"] = GroupID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotices", param); List<GroupNoticeData> values = new List<GroupNoticeData>(); if (!respData.Contains("error")) { foreach (Hashtable value in respData.Values) { GroupNoticeData data = new GroupNoticeData(); data.NoticeID = UUID.Parse((string)value["NoticeID"]); data.Timestamp = uint.Parse((string)value["Timestamp"]); data.FromName = (string)value["FromName"]; data.Subject = (string)value["Subject"]; data.HasAttachment = false; data.AssetType = 0; values.Add(data); } } return values; } public GroupNoticeInfo GetGroupNotice(UUID requestingAgentID, UUID noticeID) { Hashtable param = new Hashtable(); param["NoticeID"] = noticeID.ToString(); Hashtable respData = XmlRpcCall(requestingAgentID, "groups.getGroupNotice", param); if (respData.Contains("error")) { return null; } GroupNoticeInfo data = new GroupNoticeInfo(); data.GroupID = UUID.Parse((string)respData["GroupID"]); data.Message = (string)respData["Message"]; data.BinaryBucket = Utils.HexStringToBytes((string)respData["BinaryBucket"], true); data.noticeData.NoticeID = UUID.Parse((string)respData["NoticeID"]); data.noticeData.Timestamp = uint.Parse((string)respData["Timestamp"]); data.noticeData.FromName = (string)respData["FromName"]; data.noticeData.Subject = (string)respData["Subject"]; data.noticeData.HasAttachment = false; data.noticeData.AssetType = 0; if (data.Message == null) { data.Message = string.Empty; } return data; } public void AddGroupNotice(UUID requestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message, byte[] binaryBucket) { string binBucket = OpenMetaverse.Utils.BytesToHexString(binaryBucket, ""); Hashtable param = new Hashtable(); param["GroupID"] = groupID.ToString(); param["NoticeID"] = noticeID.ToString(); param["FromName"] = fromName; param["Subject"] = subject; param["Message"] = message; param["BinaryBucket"] = binBucket; param["TimeStamp"] = ((uint)Util.UnixTimeSinceEpoch()).ToString(); XmlRpcCall(requestingAgentID, "groups.addGroupNotice", param); } #endregion #region GroupSessionTracking public void ResetAgentGroupChatSessions(UUID agentID) { foreach (List<UUID> agentList in m_groupsAgentsDroppedFromChatSession.Values) { agentList.Remove(agentID); } } public bool hasAgentBeenInvitedToGroupChatSession(UUID agentID, UUID groupID) { // If we're tracking this group, and we can find them in the tracking, then they've been invited return m_groupsAgentsInvitedToChatSession.ContainsKey(groupID) && m_groupsAgentsInvitedToChatSession[groupID].Contains(agentID); } public bool hasAgentDroppedGroupChatSession(UUID agentID, UUID groupID) { // If we're tracking drops for this group, // and we find them, well... then they've dropped return m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID) && m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID); } public void AgentDroppedFromGroupChatSession(UUID agentID, UUID groupID) { if (m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { // If not in dropped list, add if (!m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Add(agentID); } } } public void AgentInvitedToGroupChatSession(UUID agentID, UUID groupID) { // Add Session Status if it doesn't exist for this session CreateGroupChatSessionTracking(groupID); // If nessesary, remove from dropped list if (m_groupsAgentsDroppedFromChatSession[groupID].Contains(agentID)) { m_groupsAgentsDroppedFromChatSession[groupID].Remove(agentID); } } private void CreateGroupChatSessionTracking(UUID groupID) { if (!m_groupsAgentsDroppedFromChatSession.ContainsKey(groupID)) { m_groupsAgentsDroppedFromChatSession.Add(groupID, new List<UUID>()); m_groupsAgentsInvitedToChatSession.Add(groupID, new List<UUID>()); } } #endregion #region XmlRpcHashtableMarshalling private GroupProfileData GroupProfileHashtableToGroupProfileData(Hashtable groupProfile) { GroupProfileData group = new GroupProfileData(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.Name = (string)groupProfile["Name"]; if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.InsigniaID = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRole = UUID.Parse((string)groupProfile["OwnerRoleID"]); group.GroupMembershipCount = int.Parse((string)groupProfile["GroupMembershipCount"]); group.GroupRolesCount = int.Parse((string)groupProfile["GroupRolesCount"]); return group; } private GroupRecord GroupProfileHashtableToGroupRecord(Hashtable groupProfile) { GroupRecord group = new GroupRecord(); group.GroupID = UUID.Parse((string)groupProfile["GroupID"]); group.GroupName = groupProfile["Name"].ToString(); if (groupProfile["Charter"] != null) { group.Charter = (string)groupProfile["Charter"]; } group.ShowInList = ((string)groupProfile["ShowInList"]) == "1"; group.GroupPicture = UUID.Parse((string)groupProfile["InsigniaID"]); group.MembershipFee = int.Parse((string)groupProfile["MembershipFee"]); group.OpenEnrollment = ((string)groupProfile["OpenEnrollment"]) == "1"; group.AllowPublish = ((string)groupProfile["AllowPublish"]) == "1"; group.MaturePublish = ((string)groupProfile["MaturePublish"]) == "1"; group.FounderID = UUID.Parse((string)groupProfile["FounderID"]); group.OwnerRoleID = UUID.Parse((string)groupProfile["OwnerRoleID"]); return group; } private static GroupMembershipData HashTableToGroupMembershipData(Hashtable respData) { GroupMembershipData data = new GroupMembershipData(); data.AcceptNotices = ((string)respData["AcceptNotices"] == "1"); data.Contribution = int.Parse((string)respData["Contribution"]); data.ListInProfile = ((string)respData["ListInProfile"] == "1"); data.ActiveRole = new UUID((string)respData["SelectedRoleID"]); data.GroupTitle = (string)respData["Title"]; data.GroupPowers = ulong.Parse((string)respData["GroupPowers"]); // Is this group the agent's active group data.GroupID = new UUID((string)respData["GroupID"]); UUID ActiveGroup = new UUID((string)respData["ActiveGroupID"]); data.Active = data.GroupID.Equals(ActiveGroup); data.AllowPublish = ((string)respData["AllowPublish"] == "1"); if (respData["Charter"] != null) { data.Charter = (string)respData["Charter"]; } data.FounderID = new UUID((string)respData["FounderID"]); data.GroupID = new UUID((string)respData["GroupID"]); data.GroupName = (string)respData["GroupName"]; data.GroupPicture = new UUID((string)respData["InsigniaID"]); data.MaturePublish = ((string)respData["MaturePublish"] == "1"); data.MembershipFee = int.Parse((string)respData["MembershipFee"]); data.OpenEnrollment = ((string)respData["OpenEnrollment"] == "1"); data.ShowInList = ((string)respData["ShowInList"] == "1"); return data; } #endregion /// <summary> /// Encapsulate the XmlRpc call to standardize security and error handling. /// </summary> private Hashtable XmlRpcCall(UUID requestingAgentID, string function, Hashtable param) { XmlRpcResponse resp = null; string CacheKey = null; // Only bother with the cache if it isn't disabled. if (m_cacheTimeout > 0) { if (!function.StartsWith("groups.get")) { // Any and all updates cause the cache to clear m_memoryCache.Clear(); } else { StringBuilder sb = new StringBuilder(requestingAgentID + function); foreach (object key in param.Keys) { if (param[key] != null) { sb.AppendFormat(",{0}:{1}", key.ToString(), param[key].ToString()); } } CacheKey = sb.ToString(); m_memoryCache.TryGetValue(CacheKey, out resp); } } if (resp == null) { string UserService; UUID SessionID; GetClientGroupRequestID(requestingAgentID, out UserService, out SessionID); param.Add("RequestingAgentID", requestingAgentID.ToString()); param.Add("RequestingAgentUserService", UserService); param.Add("RequestingSessionID", SessionID.ToString()); param.Add("ReadKey", m_groupReadKey); param.Add("WriteKey", m_groupWriteKey); if (m_debugEnabled) { m_log.Debug("[XMLRPCGROUPDATA] XmlRpcCall Params:"); foreach (string key in param.Keys) { m_log.DebugFormat("[XMLRPCGROUPDATA] {0} : {1}", key, param[key]); } } IList parameters = new ArrayList(); parameters.Add(param); ConfigurableKeepAliveXmlRpcRequest req; req = new ConfigurableKeepAliveXmlRpcRequest(function, parameters, m_disableKeepAlive); try { resp = req.Send(m_groupsServerURI, 10000); if ((m_cacheTimeout > 0) && (CacheKey != null)) { m_memoryCache.AddOrUpdate(CacheKey, resp, TimeSpan.FromSeconds(m_cacheTimeout)); } } catch (Exception e) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: An error has occured while attempting to access the XmlRpcGroups server method: {0}", function); m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", e.ToString()); if ((req != null) && (req.RequestResponse != null)) { foreach (string ResponseLine in req.RequestResponse.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} ", ResponseLine); } } foreach (string key in param.Keys) { m_log.WarnFormat("[XMLRPCGROUPDATA]: {0} :: {1}", key, param[key].ToString()); } Hashtable respData = new Hashtable(); respData.Add("error", e.ToString()); return respData; } } if (resp.Value is Hashtable) { Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error") && !respData.Contains("succeed")) { LogRespDataToConsoleError(function, respData); } return respData; } m_log.ErrorFormat("[XMLRPCGROUPDATA]: The XmlRpc server returned a {1} instead of a hashtable for {0}", function, resp.Value.GetType().ToString()); if (resp.Value is ArrayList) { ArrayList al = (ArrayList)resp.Value; m_log.ErrorFormat("[XMLRPCGROUPDATA]: Contains {0} elements", al.Count); foreach (object o in al) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} :: {1}", o.GetType().ToString(), o.ToString()); } } else { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Function returned: {0}", resp.Value.ToString()); } Hashtable error = new Hashtable(); error.Add("error", "invalid return value"); return error; } private void LogRespDataToConsoleError(string function, Hashtable respData) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Error data from XmlRpcGroups server method: {0}", function); m_log.Error("[XMLRPCGROUPDATA]: Error:"); foreach (string key in respData.Keys) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: Key: {0}", key); if ((respData != null) && (respData.ContainsKey(key)) && (respData[key]!=null)) { string[] lines = respData[key].ToString().Split(new char[] { '\n' }); foreach (string line in lines) { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0}", line); } } else { m_log.ErrorFormat("[XMLRPCGROUPDATA]: {0} : Empty/NULL", key); } } } /// <summary> /// Group Request Tokens are an attempt to allow the groups service to authenticate /// requests. /// TODO: This broke after the big grid refactor, either find a better way, or discard this /// </summary> /// <param name="client"></param> /// <returns></returns> private void GetClientGroupRequestID(UUID AgentID, out string UserServiceURL, out UUID SessionID) { // Default to local grid user service UserServiceURL = m_commManager.NetworkServersInfo.UserURL; ; // if AgentID == UUID, there will be no SessionID. This will be true when // the region is requesting information for region use (object permissions for example) SessionID = UUID.Zero; // Attempt to get User Profile, for SessionID UserProfileData userProfile = m_userService.GetUserProfile(AgentID); if ((userProfile != null) && (userProfile is ForeignUserProfileData)) { // They aren't from around here ForeignUserProfileData fupd = (ForeignUserProfileData)userProfile; UserServiceURL = fupd.UserServerURI; SessionID = fupd.CurrentAgent.SessionID; } else if (userProfile != null) { // Local, just use the local SessionID SessionID = userProfile.CurrentAgent.SessionID; } else if (AgentID != UUID.Zero) { // This should be impossible. If I've been passed a reference to a client // that client should be registered with the UserService. So something // is horribly wrong somewhere. // m_log.WarnFormat("[XMLRPCGROUPDATA]: Could not find a UserServiceURL for {0}", AgentID); } } } } namespace Nwc.XmlRpc { using System; using System.Collections; using System.IO; using System.Xml; using System.Net; using System.Text; using System.Reflection; /// <summary>Class supporting the request side of an XML-RPC transaction.</summary> public class ConfigurableKeepAliveXmlRpcRequest : XmlRpcRequest { private Encoding _encoding = new ASCIIEncoding(); private XmlRpcRequestSerializer _serializer = new XmlRpcRequestSerializer(); private XmlRpcResponseDeserializer _deserializer = new XmlRpcResponseDeserializer(); private bool _disableKeepAlive = true; public string RequestResponse = String.Empty; /// <summary>Instantiate an <c>XmlRpcRequest</c> for a specified method and parameters.</summary> /// <param name="methodName"><c>String</c> designating the <i>object.method</i> on the server the request /// should be directed to.</param> /// <param name="parameters"><c>ArrayList</c> of XML-RPC type parameters to invoke the request with.</param> public ConfigurableKeepAliveXmlRpcRequest(String methodName, IList parameters, bool disableKeepAlive) { MethodName = methodName; _params = parameters; _disableKeepAlive = disableKeepAlive; } /// <summary>Send the request to the server.</summary> /// <param name="url"><c>String</c> The url of the XML-RPC server.</param> /// <returns><c>XmlRpcResponse</c> The response generated.</returns> public XmlRpcResponse Send(String url) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); if (request == null) throw new XmlRpcException(XmlRpcErrorCodes.TRANSPORT_ERROR, XmlRpcErrorCodes.TRANSPORT_ERROR_MSG + ": Could not create request with " + url); request.Method = "POST"; request.ContentType = "text/xml"; request.AllowWriteStreamBuffering = true; request.KeepAlive = !_disableKeepAlive; Stream stream = request.GetRequestStream(); XmlTextWriter xml = new XmlTextWriter(stream, _encoding); _serializer.Serialize(xml, this); xml.Flush(); xml.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader input = new StreamReader(response.GetResponseStream()); string inputXml = input.ReadToEnd(); XmlRpcResponse resp; try { resp = (XmlRpcResponse)_deserializer.Deserialize(inputXml); } catch (Exception e) { RequestResponse = inputXml; throw e; } input.Close(); response.Close(); return resp; } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using System.Collections.Generic; namespace AmplifyShaderEditor { public class ShortcutItem { public delegate void ShortcutFunction(); public ShortcutFunction MyKeyDownFunctionPtr; public ShortcutFunction MyKeyUpFunctionPtr; public string Name; public string Description; public ShortcutItem( string name, string description ) { Name = name; Description = description; } public ShortcutItem( string name, string description, ShortcutFunction myKeyDownFunctionPtr, ShortcutFunction myKeyUpFunctionPtr = null ) { Name = name; Description = description; MyKeyDownFunctionPtr = myKeyDownFunctionPtr; MyKeyUpFunctionPtr = myKeyUpFunctionPtr; } public void Destroy() { MyKeyDownFunctionPtr = null; MyKeyUpFunctionPtr = null; } } public class ShortcutsManager { public static readonly KeyCode ScrollUpKey = KeyCode.PageUp; public static readonly KeyCode ScrollDownKey = KeyCode.PageDown; private const string ItemWikiFormat = "*<b>[{0}]:</b> {1}\n"; private Dictionary<KeyCode, Dictionary<EventModifiers, ShortcutItem>> m_editorShortcutsDict = new Dictionary<KeyCode, Dictionary<EventModifiers, ShortcutItem>>(); private Dictionary<KeyCode, ShortcutItem> m_editorNoModifiersShortcutsDict = new Dictionary<KeyCode, ShortcutItem>(); private List<ShortcutItem> m_editorShortcutsList = new List<ShortcutItem>(); private Dictionary<KeyCode, ShortcutItem> m_nodesShortcutsDict = new Dictionary<KeyCode, ShortcutItem>(); private List<ShortcutItem> m_nodesShortcutsList = new List<ShortcutItem>(); public void DumpShortcutsToDisk( string pathname ) { if ( !System.IO.Directory.Exists( pathname ) ) { System.IO.Directory.CreateDirectory( pathname ); } string list = "=== Full Shortcut List ===\n"; list += "==== Editor ====\n"; for ( int i = 0; i < m_editorShortcutsList.Count; i++ ) { list += string.Format( ItemWikiFormat, m_editorShortcutsList[ i ].Name, m_editorShortcutsList[ i ].Description ); } list += "\n"; list += "==== Nodes ====\n"; for ( int i = 0; i < m_nodesShortcutsList.Count; i++ ) { list += string.Format( ItemWikiFormat, m_nodesShortcutsList[ i ].Name, m_nodesShortcutsList[ i ].Description ); } string shortcutsPathnames = pathname + "KeyboardShortcuts.txt"; Debug.Log( " Creating shortcuts file at " + shortcutsPathnames ); IOUtils.SaveTextfileToDisk( list, shortcutsPathnames, false ); } public void RegisterNodesShortcuts( KeyCode key, string nodeName ) { if ( m_nodesShortcutsDict.ContainsKey( key ) ) { if ( DebugConsoleWindow.DeveloperMode ) { Debug.Log( "Attempting to register an already used node shortcut key " + key ); } return; } m_nodesShortcutsDict.Add( key, new ShortcutItem( key.ToString(), nodeName ) ); m_nodesShortcutsList.Add( m_nodesShortcutsDict[ key ] ); } public void RegisterEditorShortcut( bool showOnList, EventModifiers modifiers, KeyCode key, string description, ShortcutItem.ShortcutFunction myKeyDownFunctionPtr, ShortcutItem.ShortcutFunction myKeyUpFunctionPtr = null ) { if ( m_editorShortcutsDict.ContainsKey( key ) ) { if ( m_editorShortcutsDict[ key ].ContainsKey( modifiers ) ) { if ( DebugConsoleWindow.DeveloperMode ) { Debug.Log( "Attempting to register an already used editor shortcut key " + key ); } return; } } else { m_editorShortcutsDict.Add( key, new Dictionary<EventModifiers, ShortcutItem>() ); } ShortcutItem item = new ShortcutItem( ( modifiers == EventModifiers.None ? key.ToString() : modifiers + " + " + key ), description, myKeyDownFunctionPtr, myKeyUpFunctionPtr ); m_editorShortcutsDict[ key ].Add( modifiers, item ); if ( showOnList ) m_editorShortcutsList.Add( item ); } public void RegisterEditorShortcut( bool showOnList, KeyCode key, string description, ShortcutItem.ShortcutFunction myKeyDownFunctionPtr, ShortcutItem.ShortcutFunction myKeyUpFunctionPtr = null ) { if ( m_editorNoModifiersShortcutsDict.ContainsKey( key ) ) { if ( DebugConsoleWindow.DeveloperMode ) { Debug.Log( "Attempting to register an already used editor shortcut key " + key ); } return; } ShortcutItem item = new ShortcutItem( key.ToString(), description, myKeyDownFunctionPtr, myKeyUpFunctionPtr ); m_editorNoModifiersShortcutsDict.Add( key, item ); if ( showOnList ) m_editorShortcutsList.Add( item ); } public bool ActivateShortcut( EventModifiers modifiers, KeyCode key, bool isKeyDown ) { if ( m_editorShortcutsDict.ContainsKey( key ) ) { if ( isKeyDown ) { if ( m_editorShortcutsDict[ key ].ContainsKey( modifiers ) ) { if ( m_editorShortcutsDict[ key ][ modifiers ].MyKeyDownFunctionPtr != null ) { m_editorShortcutsDict[ key ][ modifiers ].MyKeyDownFunctionPtr(); return true; } } } else { if ( m_editorShortcutsDict[ key ].ContainsKey( modifiers ) ) { if ( m_editorShortcutsDict[ key ][ modifiers ].MyKeyUpFunctionPtr != null ) { m_editorShortcutsDict[ key ][ modifiers ].MyKeyUpFunctionPtr(); return true; } } } } if ( m_editorNoModifiersShortcutsDict.ContainsKey( key ) ) { if ( isKeyDown ) { if ( m_editorNoModifiersShortcutsDict[ key ].MyKeyDownFunctionPtr != null ) { m_editorNoModifiersShortcutsDict[ key ].MyKeyDownFunctionPtr(); return true; } } else { if ( m_editorNoModifiersShortcutsDict[ key ].MyKeyUpFunctionPtr != null ) { m_editorNoModifiersShortcutsDict[ key ].MyKeyUpFunctionPtr(); return true; } } } return false; } public void Destroy() { foreach ( KeyValuePair<KeyCode, ShortcutItem> kvp in m_editorNoModifiersShortcutsDict ) { kvp.Value.Destroy(); } m_editorNoModifiersShortcutsDict.Clear(); m_editorNoModifiersShortcutsDict = null; foreach ( KeyValuePair<KeyCode, Dictionary<EventModifiers, ShortcutItem>> kvpKey in m_editorShortcutsDict ) { foreach ( KeyValuePair<EventModifiers, ShortcutItem> kvpMod in kvpKey.Value ) { kvpMod.Value.Destroy(); } kvpKey.Value.Clear(); } m_editorShortcutsDict.Clear(); m_editorShortcutsDict = null; m_editorShortcutsList.Clear(); m_editorShortcutsList = null; m_nodesShortcutsDict.Clear(); m_nodesShortcutsDict = null; m_nodesShortcutsList.Clear(); m_nodesShortcutsList = null; } public List<ShortcutItem> AvailableEditorShortcutsList { get { return m_editorShortcutsList; } } public List<ShortcutItem> AvailableNodesShortcutsList { get { return m_nodesShortcutsList; } } } }
// // Mono.Data.SybaseTypes.SybaseByte // // Author: // Tim Coleman <tim@timcoleman.com> // // Based on System.Data.SqlTypes.SqlByte // // // (C) Ximian, Inc. 2002-2003 // (C) Copyright Tim Coleman, 2002 // // // 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 Mono.Data.SybaseClient; using System; using System.Data.SqlTypes; using System.Globalization; namespace Mono.Data.SybaseTypes { public struct SybaseByte : INullable, IComparable { #region Fields byte value; private bool notNull; public static readonly SybaseByte MaxValue = new SybaseByte (0xff); public static readonly SybaseByte MinValue = new SybaseByte (0); public static readonly SybaseByte Null; public static readonly SybaseByte Zero = new SybaseByte (0); #endregion #region Constructors public SybaseByte (byte value) { this.value = value; notNull = true; } #endregion #region Properties public bool IsNull { get { return !notNull; } } public byte Value { get { if (this.IsNull) throw new SybaseNullValueException (); else return value; } } #endregion #region Methods public static SybaseByte Add (SybaseByte x, SybaseByte y) { return (x + y); } public static SybaseByte BitwiseAnd (SybaseByte x, SybaseByte y) { return (x & y); } public static SybaseByte BitwiseOr (SybaseByte x, SybaseByte y) { return (x | y); } public int CompareTo (object value) { if (value == null) return 1; else if (!(value is SybaseByte)) throw new ArgumentException (Locale.GetText ("Value is not a System.Data.SybaseTypes.SybaseByte")); else if (((SybaseByte)value).IsNull) return 1; else return this.value.CompareTo (((SybaseByte)value).Value); } public static SybaseByte Divide (SybaseByte x, SybaseByte y) { return (x / y); } public override bool Equals (object value) { if (!(value is SybaseByte)) return false; else return (bool) (this == (SybaseByte)value); } public static SybaseBoolean Equals (SybaseByte x, SybaseByte y) { return (x == y); } public override int GetHashCode () { return (int)value; } public static SybaseBoolean GreaterThan (SybaseByte x, SybaseByte y) { return (x > y); } public static SybaseBoolean GreaterThanOrEqual (SybaseByte x, SybaseByte y) { return (x >= y); } public static SybaseBoolean LessThan (SybaseByte x, SybaseByte y) { return (x < y); } public static SybaseBoolean LessThanOrEqual (SybaseByte x, SybaseByte y) { return (x <= y); } public static SybaseByte Mod (SybaseByte x, SybaseByte y) { return (x % y); } public static SybaseByte Multiply (SybaseByte x, SybaseByte y) { return (x * y); } public static SybaseBoolean NotEquals (SybaseByte x, SybaseByte y) { return (x != y); } public static SybaseByte OnesComplement (SybaseByte x) { return ~x; } public static SybaseByte Parse (string s) { return new SybaseByte (Byte.Parse (s)); } public static SybaseByte Subtract (SybaseByte x, SybaseByte y) { return (x - y); } public SybaseBoolean ToSybaseBoolean () { return ((SybaseBoolean)this); } public SybaseDecimal ToSybaseDecimal () { return ((SybaseDecimal)this); } public SybaseDouble ToSybaseDouble () { return ((SybaseDouble)this); } public SybaseInt16 ToSybaseInt16 () { return ((SybaseInt16)this); } public SybaseInt32 ToSybaseInt32 () { return ((SybaseInt32)this); } public SybaseInt64 ToSybaseInt64 () { return ((SybaseInt64)this); } public SybaseMoney ToSybaseMoney () { return ((SybaseMoney)this); } public SybaseSingle ToSybaseSingle () { return ((SybaseSingle)this); } public SybaseString ToSybaseString () { return ((SybaseString)this); } public override string ToString () { if (this.IsNull) return "Null"; else return value.ToString (); } public static SybaseByte Xor (SybaseByte x, SybaseByte y) { return (x ^ y); } public static SybaseByte operator + (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value + y.Value)); } public static SybaseByte operator & (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value & y.Value)); } public static SybaseByte operator | (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value | y.Value)); } public static SybaseByte operator / (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value / y.Value)); } public static SybaseBoolean operator == (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value == y.Value); } public static SybaseByte operator ^ (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value ^ y.Value)); } public static SybaseBoolean operator > (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value > y.Value); } public static SybaseBoolean operator >= (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value >= y.Value); } public static SybaseBoolean operator != (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (!(x.Value == y.Value)); } public static SybaseBoolean operator < (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value < y.Value); } public static SybaseBoolean operator <= (SybaseByte x, SybaseByte y) { if (x.IsNull || y.IsNull) return SybaseBoolean.Null; else return new SybaseBoolean (x.Value <= y.Value); } public static SybaseByte operator % (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value % y.Value)); } public static SybaseByte operator * (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value * y.Value)); } public static SybaseByte operator ~ (SybaseByte x) { return new SybaseByte ((byte) ~x.Value); } public static SybaseByte operator - (SybaseByte x, SybaseByte y) { return new SybaseByte ((byte) (x.Value - y.Value)); } public static explicit operator SybaseByte (SybaseBoolean x) { if (x.IsNull) return Null; else return new SybaseByte (x.ByteValue); } public static explicit operator byte (SybaseByte x) { return x.Value; } public static explicit operator SybaseByte (SybaseDecimal x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseDouble x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseInt16 x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseInt32 x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseInt64 x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseMoney x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseSingle x) { if (x.IsNull) return Null; else return new SybaseByte ((byte)x.Value); } public static explicit operator SybaseByte (SybaseString x) { return SybaseByte.Parse (x.Value); } public static implicit operator SybaseByte (byte x) { return new SybaseByte (x); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlServerCe; using System.Collections; using System.Windows.Forms; using DowUtils; namespace Factotum{ public class EComponentMaterial : IEntity { public static event EventHandler<EntityChangedEventArgs> Changed; protected virtual void OnChanged(Guid? ID) { // Copy to a temporary variable to be thread-safe. EventHandler<EntityChangedEventArgs> temp = Changed; if (temp != null) temp(this, new EntityChangedEventArgs(ID)); } // Mapped database columns // Use Guid?s for Primary Keys and foreign keys (whether they're nullable or not). // Use int?, decimal?, etc for numbers (whether they're nullable or not). // Strings, images, etc, are reference types already private Guid? CmtDBid; private string CmtName; private Guid? CmtSitID; private byte? CmtCalBlockMaterial; private bool CmtIsLclChg; private bool CmtIsActive; // Textbox limits public static int CmtNameCharLimit = 25; public static int CmtCalBlockMaterialCharLimit = 3; // Field-specific error message strings (normally just needed for textbox data) private string CmtNameErrMsg; private string CmtCalBlockMaterialErrMsg; // Form level validation message private string CmtErrMsg; //-------------------------------------------------------- // Field Properties //-------------------------------------------------------- // Primary key accessor public Guid? ID { get { return CmtDBid; } } public string CmpMaterialName { get { return CmtName; } set { CmtName = Util.NullifyEmpty(value); } } public Guid? CmpMaterialSitID { get { return CmtSitID; } set { CmtSitID = value; } } public byte? CmpMaterialCalBlockMaterial { get { return CmtCalBlockMaterial; } set { CmtCalBlockMaterial = value; } } public bool CmpMaterialIsLclChg { get { return CmtIsLclChg; } set { CmtIsLclChg = value; } } public bool CmpMaterialIsActive { get { return CmtIsActive; } set { CmtIsActive = value; } } //----------------------------------------------------------------- // Field Level Error Messages. // Include one for every text column // In cases where we need to ensure data consistency, we may need // them for other types. //----------------------------------------------------------------- public string CmpMaterialNameErrMsg { get { return CmtNameErrMsg; } } public string CmpMaterialCalBlockMaterialErrMsg { get { return CmtCalBlockMaterialErrMsg; } } //-------------------------------------- // Form level Error Message //-------------------------------------- public string CmpMaterialErrMsg { get { return CmtErrMsg; } set { CmtErrMsg = Util.NullifyEmpty(value); } } //-------------------------------------- // Textbox Name Length Validation //-------------------------------------- public bool CmpMaterialNameLengthOk(string s) { if (s == null) return true; if (s.Length > CmtNameCharLimit) { CmtNameErrMsg = string.Format("Component Material Names cannot exceed {0} characters", CmtNameCharLimit); return false; } else { CmtNameErrMsg = null; return true; } } //-------------------------------------- // Field-Specific Validation // sets and clears error messages //-------------------------------------- public bool CmpMaterialNameValid(string name) { bool existingIsInactive; if (!CmpMaterialNameLengthOk(name)) return false; // KEEP, MODIFY OR REMOVE THIS AS REQUIRED // YOU MAY NEED THE NAME TO BE UNIQUE FOR A SPECIFIC PARENT, ETC.. if (NameExistsForSite(name, CmtDBid, (Guid)CmtSitID, out existingIsInactive)) { CmtNameErrMsg = existingIsInactive ? "A Component Material with that name exists but its status has been set to inactive." : "That Component Material Name is already in use."; return false; } CmtNameErrMsg = null; return true; } public bool CmpMaterialCalBlockMaterialValid(byte? value) { // Add some real validation here if needed. CmtCalBlockMaterialErrMsg = null; return true; } //-------------------------------------- // Constructors //-------------------------------------- // Default constructor. Field defaults must be set here. // Any defaults set by the database will be overridden. public EComponentMaterial() { this.CmtCalBlockMaterial = 1; this.CmtIsLclChg = false; this.CmtIsActive = true; } // Constructor which loads itself from the supplied id. // If the id is null, this gives the same result as using the default constructor. public EComponentMaterial(Guid? id) : this() { Load(id); } //-------------------------------------- // Public Methods //-------------------------------------- //---------------------------------------------------- // Load the object from the database given a Guid? //---------------------------------------------------- public void Load(Guid? id) { if (id == null) return; SqlCeCommand cmd = Globals.cnn.CreateCommand(); SqlCeDataReader dr; cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select CmtDBid, CmtName, CmtSitID, CmtCalBlockMaterial, CmtIsLclChg, CmtIsActive from ComponentMaterials where CmtDBid = @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // The query should return one record. // If it doesn't return anything (no match) the object is not affected if (dr.Read()) { // For nullable foreign keys, set field to null for dbNull case // For other nullable values, replace dbNull with null CmtDBid = (Guid?)dr[0]; CmtName = (string)dr[1]; CmtSitID = (Guid?)dr[2]; CmtCalBlockMaterial = (byte?)dr[3]; CmtIsLclChg = (bool)dr[4]; CmtIsActive = (bool)dr[5]; } dr.Close(); } //-------------------------------------- // Save the current record if it's valid //-------------------------------------- public Guid? Save() { if (!Valid()) { // Note: We're returning null if we fail, // so don't just assume you're going to get your id back // and set your id to the result of this function call. return null; } SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; if (ID == null) { // we are inserting a new record // If this is not a master db, set the local change flag to true. if (!Globals.IsMasterDB) CmtIsLclChg = true; // first ask the database for a new Guid cmd.CommandText = "Select Newid()"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); CmtDBid = (Guid?)(cmd.ExecuteScalar()); // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", CmtDBid), new SqlCeParameter("@p1", CmtName), new SqlCeParameter("@p2", CmtSitID), new SqlCeParameter("@p3", CmtCalBlockMaterial), new SqlCeParameter("@p4", CmtIsLclChg), new SqlCeParameter("@p5", CmtIsActive) }); cmd.CommandText = @"Insert Into ComponentMaterials ( CmtDBid, CmtName, CmtSitID, CmtCalBlockMaterial, CmtIsLclChg, CmtIsActive ) values (@p0,@p1,@p2,@p3,@p4,@p5)"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to insert ComponentMaterials row"); } } else { // we are updating an existing record // Replace any nulls with dbnull cmd.Parameters.AddRange(new SqlCeParameter[] { new SqlCeParameter("@p0", CmtDBid), new SqlCeParameter("@p1", CmtName), new SqlCeParameter("@p2", CmtSitID), new SqlCeParameter("@p3", CmtCalBlockMaterial), new SqlCeParameter("@p4", CmtIsLclChg), new SqlCeParameter("@p5", CmtIsActive)}); cmd.CommandText = @"Update ComponentMaterials set CmtName = @p1, CmtSitID = @p2, CmtCalBlockMaterial = @p3, CmtIsLclChg = @p4, CmtIsActive = @p5 Where CmtDBid = @p0"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if (cmd.ExecuteNonQuery() != 1) { throw new Exception("Unable to update component materials row"); } } OnChanged(ID); return ID; } //-------------------------------------- // Validate the current record //-------------------------------------- // Make this public so that the UI can check validation itself // if it chooses to do so. This is also called by the Save function. public bool Valid() { // First check each field to see if it's valid from the UI perspective if (!CmpMaterialNameValid(CmpMaterialName)) return false; if (!CmpMaterialCalBlockMaterialValid(CmpMaterialCalBlockMaterial)) return false; // Check form to make sure all required fields have been filled in if (!RequiredFieldsFilled()) return false; // Check for incorrect field interactions... return true; } //-------------------------------------- // Delete the current record //-------------------------------------- public bool Delete(bool promptUser) { // If the current object doesn't reference a database record, there's nothing to do. if (CmtDBid == null) { CmpMaterialErrMsg = "Unable to delete. Record not found."; return false; } if (!CmtIsLclChg && !Globals.IsMasterDB) { CmpMaterialErrMsg = "Unable to delete because this Component Material was not added during this outage.\r\nYou may wish to inactivate it instead."; return false; } if (HasChildren()) { CmpMaterialErrMsg = "Unable to delete because components exist with this material type."; return false; } DialogResult rslt = DialogResult.None; if (promptUser) { rslt = MessageBox.Show("Are you sure?", "Factotum: Deleting...", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); } if (!promptUser || rslt == DialogResult.OK) { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Delete from ComponentMaterials where CmtDBid = @p0"; cmd.Parameters.Add("@p0", CmtDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); int rowsAffected = cmd.ExecuteNonQuery(); // Todo: figure out how I really want to do this. // Is there a problem with letting the database try to do cascading deletes? // How should the user be notified of the problem?? if (rowsAffected < 1) { CmpMaterialErrMsg = "Unable to delete. Please try again later."; return false; } else { OnChanged(ID); return true; } } else { CmpMaterialErrMsg = null; return false; } } // Check whether the current record is referenced by other tables. private bool HasChildren() { SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = @"Select CmpDBid from Components where CmpCmtID = @p0"; cmd.Parameters.Add("@p0", CmtDBid); if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object result = cmd.ExecuteScalar(); return result != null; } //-------------------------------------------------------------------- // Static listing methods which return collections of cmpmaterials //-------------------------------------------------------------------- // This helper function builds the collection for you based on the flags you send it // I originally had a flag that would let you indicate inactive items by appending '(inactive)' // to the name. This was a bad idea, because sometimes the objects in this collection // will get modified and saved back to the database -- with the extra text appended to the name. public static EComponentMaterialCollection ListByName( bool showactive, bool showinactive, bool addNoSelection) { EComponentMaterial cmpmaterial; EComponentMaterialCollection cmpmaterials = new EComponentMaterialCollection(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select CmtDBid, CmtName, CmtSitID, CmtCalBlockMaterial, CmtIsLclChg, CmtIsActive from ComponentMaterials"; if (showactive && !showinactive) qry += " where CmtIsActive = 1"; else if (!showactive && showinactive) qry += " where CmtIsActive = 0"; qry += " order by CmtName"; cmd.CommandText = qry; if (addNoSelection) { // Insert a default item with name "<No Selection>" cmpmaterial = new EComponentMaterial(); cmpmaterial.CmtName = "<No Selection>"; cmpmaterials.Add(cmpmaterial); } SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { cmpmaterial = new EComponentMaterial((Guid?)dr[0]); cmpmaterial.CmtName = (string)(dr[1]); cmpmaterial.CmtSitID = (Guid?)(dr[2]); cmpmaterial.CmtCalBlockMaterial = (byte?)(dr[3]); cmpmaterial.CmtIsLclChg = (bool)(dr[4]); cmpmaterial.CmtIsActive = (bool)(dr[5]); cmpmaterials.Add(cmpmaterial); } // Finish up dr.Close(); return cmpmaterials; } // This helper function builds the collection for you based on the flags you send it // To fill a checked listbox you may want to set 'includeUnassigned' // To fill a treeview or combo box, you probably don't. public static EComponentMaterialCollection ListForSite(Guid? SiteID, bool showinactive, bool addNoSelection) { EComponentMaterial cmpmaterial; EComponentMaterialCollection cmpmaterials = new EComponentMaterialCollection(); if (addNoSelection) { // Insert a default item with name "<No Selection>" cmpmaterial = new EComponentMaterial(); cmpmaterial.CmtName = "<No Selection>"; cmpmaterials.Add(cmpmaterial); } if (SiteID == null) return cmpmaterials; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; string qry = @"Select CmtDBid, CmtName, CmtSitID, CmtCalBlockMaterial, CmtIsLclChg, CmtIsActive from ComponentMaterials"; qry += " where CmtSitID = @p1"; if (!showinactive) qry += " and CmtIsActive = 1"; qry += " order by CmtName"; cmd.CommandText = qry; cmd.Parameters.Add(new SqlCeParameter("@p1", SiteID)); SqlCeDataReader dr; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); dr = cmd.ExecuteReader(); // Build new objects and add them to the collection while (dr.Read()) { cmpmaterial = new EComponentMaterial((Guid?)dr[0]); cmpmaterial.CmtName = (string)(dr[1]); cmpmaterial.CmtSitID = (Guid?)(dr[2]); cmpmaterial.CmtCalBlockMaterial = (byte?)(dr[3]); cmpmaterial.CmtIsLclChg = (bool)(dr[4]); cmpmaterial.CmtIsActive = (bool)(dr[5]); cmpmaterials.Add(cmpmaterial); } // Finish up dr.Close(); return cmpmaterials; } // Get a Default data view with all columns that a user would likely want to see. // You can bind this view to a DataGridView, hide the columns you don't need, filter, etc. // I decided not to indicate inactive in the names of inactive items. The 'user' // can always show the inactive column if they wish. public static DataView GetDefaultDataView() { DataSet ds = new DataSet(); DataView dv; SqlCeDataAdapter da = new SqlCeDataAdapter(); SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; // Changing the booleans to 'Yes' and 'No' eliminates the silly checkboxes and // makes the column sortable. // You'll likely want to modify this query further, joining in other tables, etc. string qry = @"Select CmtDBid as ID, CmtName as CmpMaterialName, CmtSitID as CmpMaterialSitID, CASE WHEN CmtCalBlockMaterial = 1 Then 'Carbon Steel' WHEN CmtCalBlockMaterial = 2 Then 'Stainless Steel' WHEN CmtCalBlockMaterial = 3 Then 'Inconel' ELSE 'Unknown Material' END as CmpMaterialCalBlockMaterial, CASE WHEN CmtIsLclChg = 0 THEN 'No' ELSE 'Yes' END as CmpMaterialIsLclChg, CASE WHEN CmtIsActive = 0 THEN 'No' ELSE 'Yes' END as CmpMaterialIsActive from ComponentMaterials"; cmd.CommandText = qry; da.SelectCommand = cmd; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); da.Fill(ds); dv = new DataView(ds.Tables[0]); return dv; } public static EComponentMaterial FindForComponentMaterialName(string ComponentMaterialName) { if (Util.IsNullOrEmpty(ComponentMaterialName)) return null; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.Parameters.Add(new SqlCeParameter("@p1", ComponentMaterialName)); cmd.CommandText = "Select CmtDBid from ComponentMaterials where CmtName = @p1"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object val = cmd.ExecuteScalar(); bool exists = (val != null); if (exists) return new EComponentMaterial((Guid)val); else return null; } //-------------------------------------- // Private utilities //-------------------------------------- // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. private bool NameExists(string name, Guid? id, out bool existingIsInactive) { existingIsInactive = false; if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); if (id == null) { cmd.CommandText = "Select CmtDBid from ComponentMaterials where CmtName = @p1"; } else { cmd.CommandText = "Select CmtDBid from ComponentMaterials where CmtName = @p1 and CmtDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object val = cmd.ExecuteScalar(); bool exists = (val != null); if (exists) existingIsInactive = !(bool)val; return exists; } // Check if the name exists for any records besides the current one // This is used to show an error when the user tabs away from the field. // We don't want to show an error if the user has left the field blank. // If it's a required field, we'll catch it when the user hits save. public static bool NameExistsForSite(string name, Guid? id, Guid siteId, out bool existingIsInactive) { existingIsInactive = false; if (Util.IsNullOrEmpty(name)) return false; SqlCeCommand cmd = Globals.cnn.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(new SqlCeParameter("@p1", name)); cmd.Parameters.Add(new SqlCeParameter("@p2", siteId)); if (id == null) { cmd.CommandText = @"Select CmtIsActive from ComponentMaterials where LTRIM(RTRIM(CmtName)) = @p1 and CmtSitID = @p2"; } else { cmd.CommandText = @"Select CmtIsActive from ComponentMaterials where LTRIM(RTRIM(CmtName)) = @p1 and CmtSitID = @p2 and CmtDBid != @p0"; cmd.Parameters.Add(new SqlCeParameter("@p0", id)); } if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); object val = cmd.ExecuteScalar(); if (val == null) { return false; } bool exists = (val != null); if (exists) existingIsInactive = !(bool)val; return exists; } // Check for required fields, setting the individual error messages private bool RequiredFieldsFilled() { bool allFilled = true; if (CmpMaterialName == null) { CmtNameErrMsg = "A unique Component Material Name is required"; allFilled = false; } else { CmtNameErrMsg = null; } if (CmpMaterialCalBlockMaterial == null) { CmtCalBlockMaterialErrMsg = "A Calibration block material is required"; allFilled = false; } else { CmtCalBlockMaterialErrMsg = null; } return allFilled; } } //-------------------------------------- // CmpMaterial Collection class //-------------------------------------- public class EComponentMaterialCollection : CollectionBase { //this event is fired when the collection's items have changed public event EventHandler Changed; //this is the constructor of the collection. public EComponentMaterialCollection() { } //the indexer of the collection public EComponentMaterial this[int index] { get { return (EComponentMaterial)this.List[index]; } } //this method fires the Changed event. protected virtual void OnChanged(EventArgs e) { if (Changed != null) { Changed(this, e); } } public bool ContainsID(Guid? ID) { if (ID == null) return false; foreach (EComponentMaterial cmpmaterial in InnerList) { if (cmpmaterial.ID == ID) return true; } return false; } //returns the index of an item in the collection public int IndexOf(EComponentMaterial item) { return InnerList.IndexOf(item); } //adds an item to the collection public void Add(EComponentMaterial item) { this.List.Add(item); OnChanged(EventArgs.Empty); } //inserts an item in the collection at a specified index public void Insert(int index, EComponentMaterial item) { this.List.Insert(index, item); OnChanged(EventArgs.Empty); } //removes an item from the collection. public void Remove(EComponentMaterial item) { this.List.Remove(item); OnChanged(EventArgs.Empty); } } }
// ReSharper disable InconsistentNaming using System; using System.Collections.Generic; using System.Text; using EasyNetQ.Consumer; using EasyNetQ.Tests.Mocking; using NUnit.Framework; using RabbitMQ.Client; using Rhino.Mocks; namespace EasyNetQ.Tests { [TestFixture] public class When_using_default_conventions { private Conventions conventions; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); conventions = new Conventions(typeNameSerializer); } [Test] public void The_default_exchange_naming_convention_should_use_the_TypeNameSerializers_Serialize_method() { var result = conventions.ExchangeNamingConvention(typeof (TestMessage)); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage))); } [Test] public void The_default_topic_naming_convention_should_return_an_empty_string() { var result = conventions.TopicNamingConvention(typeof (TestMessage)); result.ShouldEqual(""); } [Test] public void The_default_queue_naming_convention_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id() { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(typeof (TestMessage), subscriptionId); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage)) + "_" + subscriptionId); } [Test] public void The_default_error_queue_name_should_be() { var result = conventions.ErrorQueueNamingConvention(); result.ShouldEqual("EasyNetQ_Default_Error_Queue"); } [Test] public void The_default_error_exchange_name_should_be() { var info = new MessageReceivedInfo("consumer_tag", 0, false, "exchange", "routingKey", "queue"); var result = conventions.ErrorExchangeNamingConvention(info); result.ShouldEqual("ErrorExchange_routingKey"); } [Test] public void The_default_rpc_exchange_name_should_be() { var result = conventions.RpcExchangeNamingConvention(); result.ShouldEqual("easy_net_q_rpc"); } [Test] public void The_default_rpc_routingkey_naming_convention_should_use_the_TypeNameSerializers_Serialize_method() { var result = conventions.RpcRoutingKeyNamingConvention(typeof(TestMessage)); result.ShouldEqual(typeNameSerializer.Serialize(typeof(TestMessage))); } } [TestFixture] public class When_using_QueueAttribute { private Conventions conventions; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); conventions = new Conventions(typeNameSerializer); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void The_queue_naming_convention_should_use_attribute_queueName_then_an_underscore_then_the_subscription_id(Type messageType) { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual("MyQueue" + "_" + subscriptionId); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void And_subscription_id_is_empty_the_queue_naming_convention_should_use_attribute_queueName(Type messageType) { const string subscriptionId = ""; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual("MyQueue"); } [Test] [TestCase(typeof(EmptyQueueNameAnnotatedTestMessage))] [TestCase(typeof(IEmptyQueueNameAnnotatedTestMessage))] public void And_queueName_is_empty_should_use_the_TypeNameSerializers_Serialize_method_then_an_underscore_then_the_subscription_id(Type messageType) { const string subscriptionId = "test"; var result = conventions.QueueNamingConvention(messageType, subscriptionId); result.ShouldEqual(typeNameSerializer.Serialize(messageType) + "_" + subscriptionId); } [Test] [TestCase(typeof(AnnotatedTestMessage))] [TestCase(typeof(IAnnotatedTestMessage))] public void The_exchange_name_convention_should_use_attribute_exchangeName(Type messageType) { var result = conventions.ExchangeNamingConvention(messageType); result.ShouldEqual("MyExchange"); } [Test] [TestCase(typeof(QueueNameOnlyAnnotatedTestMessage))] [TestCase(typeof(IQueueNameOnlyAnnotatedTestMessage))] public void And_exchangeName_not_specified_the_exchange_name_convention_should_use_the_TypeNameSerializers_Serialize_method(Type messageType) { var result = conventions.ExchangeNamingConvention(messageType); result.ShouldEqual(typeNameSerializer.Serialize(messageType)); } } [TestFixture] public class When_publishing_a_message { private MockBuilder mockBuilder; private ITypeNameSerializer typeNameSerializer; [SetUp] public void SetUp() { typeNameSerializer = new TypeNameSerializer(); var customConventions = new Conventions(typeNameSerializer) { ExchangeNamingConvention = x => "CustomExchangeNamingConvention", QueueNamingConvention = (x, y) => "CustomQueueNamingConvention", TopicNamingConvention = x => "CustomTopicNamingConvention" }; mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions)); mockBuilder.Bus.Publish(new TestMessage()); } [Test] public void Should_use_exchange_name_from_conventions_to_create_the_exchange() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomExchangeNamingConvention", "topic", true, false, new Dictionary<string, object>())); } [Test] public void Should_use_exchange_name_from_conventions_as_the_exchange_to_publish_to() { mockBuilder.Channels[0].AssertWasCalled(x => x.BasicPublish( Arg<string>.Is.Equal("CustomExchangeNamingConvention"), Arg<string>.Is.Anything, Arg<bool>.Is.Equal(false), Arg<IBasicProperties>.Is.Anything, Arg<byte[]>.Is.Anything)); } [Test] public void Should_use_topic_name_from_conventions_as_the_topic_to_publish_to() { mockBuilder.Channels[0].AssertWasCalled(x => x.BasicPublish( Arg<string>.Is.Anything, Arg<string>.Is.Equal("CustomTopicNamingConvention"), Arg<bool>.Is.Equal(false), Arg<IBasicProperties>.Is.Anything, Arg<byte[]>.Is.Anything)); } } [TestFixture] public class When_registering_response_handler { private MockBuilder mockBuilder; [SetUp] public void SetUp() { var customConventions = new Conventions(new TypeNameSerializer()) { RpcExchangeNamingConvention = () => "CustomRpcExchangeName", RpcRoutingKeyNamingConvention = messageType => "CustomRpcRoutingKeyName" }; mockBuilder = new MockBuilder(x => x.Register<IConventions>(_ => customConventions)); mockBuilder.Bus.Respond<TestMessage, TestMessage>(t => new TestMessage()); } [Test] public void Should_correctly_bind_using_new_conventions() { mockBuilder.Channels[0].AssertWasCalled(x => x.QueueBind( "CustomRpcRoutingKeyName", "CustomRpcExchangeName", "CustomRpcRoutingKeyName")); } [Test] public void Should_declare_correct_exchange() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomRpcExchangeName", "direct", true, false, new Dictionary<string, object>())); } } [TestFixture] public class When_using_default_consumer_error_strategy { private DefaultConsumerErrorStrategy errorStrategy; private MockBuilder mockBuilder; private AckStrategy errorAckStrategy; private AckStrategy cancelAckStrategy; [SetUp] public void SetUp() { var customConventions = new Conventions(new TypeNameSerializer()) { ErrorQueueNamingConvention = () => "CustomEasyNetQErrorQueueName", ErrorExchangeNamingConvention = info => "CustomErrorExchangePrefixName." + info.RoutingKey }; mockBuilder = new MockBuilder(); errorStrategy = new DefaultConsumerErrorStrategy( mockBuilder.ConnectionFactory, new JsonSerializer(new TypeNameSerializer()), MockRepository.GenerateStub<IEasyNetQLogger>(), customConventions, new TypeNameSerializer(), new DefaultErrorMessageSerializer()); const string originalMessage = ""; var originalMessageBody = Encoding.UTF8.GetBytes(originalMessage); var context = new ConsumerExecutionContext( (bytes, properties, arg3) => null, new MessageReceivedInfo("consumerTag", 0, false, "orginalExchange", "originalRoutingKey", "queue"), new MessageProperties { CorrelationId = string.Empty, AppId = string.Empty }, originalMessageBody, MockRepository.GenerateStub<IBasicConsumer>() ); try { errorAckStrategy = errorStrategy.HandleConsumerError(context, new Exception()); cancelAckStrategy = errorStrategy.HandleConsumerCancelled(context); } catch (Exception) { // swallow } } [Test] public void Should_use_exchange_name_from_custom_names_provider() { mockBuilder.Channels[0].AssertWasCalled(x => x.ExchangeDeclare("CustomErrorExchangePrefixName.originalRoutingKey", "direct", true)); } [Test] public void Should_use_queue_name_from_custom_names_provider() { mockBuilder.Channels[0].AssertWasCalled(x => x.QueueDeclare("CustomEasyNetQErrorQueueName", true, false, false, null)); } [Test] public void Should_Ack_failed_message() { Assert.AreSame(AckStrategies.Ack, errorAckStrategy); } [Test] public void Should_Ack_canceled_message() { Assert.AreSame(AckStrategies.Ack, cancelAckStrategy); } } } // ReSharper restore InconsistentNaming
using System; using System.Diagnostics.CodeAnalysis; using System.Text; using ToolKit.Validation; namespace ToolKit.DirectoryServices { /// <summary> /// The Lightweight Directory Access Protocol (LDAP) defines a network representation of a /// search filter transmitted to an LDAP server. This class attempts to represent these filters /// in a human-readable form as defined in RFC 2254 and RFC 1960. No attempt to parse the filter /// is done in this class and should support both LDAP V2 and LDAP V3 filters. /// </summary> public class LdapFilter { private readonly string _filter; /// <summary> /// Initializes a new instance of the <see cref="LdapFilter" /> class. /// </summary> /// <param name="attributeType">The attribute of the filter.</param> /// <param name="filterType">The type of the filter.</param> /// <param name="attributeValue">The value of the filter.</param> public LdapFilter(string attributeType, string filterType, string attributeValue) { _filter = $"{attributeType}{filterType}{attributeValue}"; } /// <summary> /// Initializes a new instance of the <see cref="LdapFilter" /> class. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> public LdapFilter(string ldapFilter) { _filter = Strip(Check.NotEmpty(ldapFilter, nameof(ldapFilter))); } /// <summary> /// Prevents a default instance of the <see cref="LdapFilter" /> class from being created. /// </summary> [ExcludeFromCodeCoverage] private LdapFilter() { } /// <summary> /// Gets the value that cn be used in the attributeValue as a wild card. /// </summary> public static string Any => "*"; /// <summary> /// Gets the value that can be used in the filterType to express approximation. /// </summary> public static string Approx => "~="; /// <summary> /// Gets the value that can be used in the filterType to express equality. /// </summary> public static string Equal => "="; /// <summary> /// Gets the value that can be used in the filterType to express Greater Than. /// </summary> public static string Greater => ">="; /// <summary> /// Gets the value that can be used in the filterType to express Less Than. /// </summary> public static string Less => "<="; /// <summary> /// Combines the provided LDAP filter(s) to create a new And LDAP Filter. /// </summary> /// <param name="filters">A LDAP Filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public static LdapFilter And(params LdapFilter[] filters) { var newFilter = new StringBuilder(); newFilter.Append("(&"); foreach (var filter in filters) { newFilter.Append(filter.ToString()); } newFilter.Append(')'); return new LdapFilter(newFilter.ToString()); } /// <summary> /// Combines the provided LDAP filter(s) to create a new Or LDAP Filter. /// </summary> /// <param name="filters">A LDAP Filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public static LdapFilter Or(params LdapFilter[] filters) { var newFilter = new StringBuilder(); newFilter.Append("(|"); foreach (var filter in filters) { newFilter.Append(filter.ToString()); } newFilter.Append(')'); return new LdapFilter(newFilter.ToString()); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="attributeType">The attribute of the filter.</param> /// <param name="filterType">The type of the filter.</param> /// <param name="attributeValue">The value of the filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And(string attributeType, string filterType, string attributeValue) { return And(new LdapFilter(attributeType, filterType, attributeValue), false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="attributeType">The attribute of the filter.</param> /// <param name="filterType">The type of the filter.</param> /// <param name="attributeValue">The value of the filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And( string attributeType, string filterType, string attributeValue, bool appendFilter) { return And(new LdapFilter(attributeType, filterType, attributeValue), appendFilter); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And(string ldapFilter) { return And(ldapFilter, false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And(string ldapFilter, bool appendFilter) { Check.NotEmpty(ldapFilter, nameof(ldapFilter)); return appendFilter ? new LdapFilter($"(&({_filter})({Strip(ldapFilter)}))") : new LdapFilter($"(&({Strip(ldapFilter)})({_filter}))"); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And(LdapFilter ldapFilter) { return And(Check.NotNull(ldapFilter, nameof(ldapFilter)).ToString(), false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new And LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an And LDAP Filter.</returns> public LdapFilter And(LdapFilter ldapFilter, bool appendFilter) { return And(Check.NotNull(ldapFilter, nameof(ldapFilter)).ToString(), appendFilter); } /// <summary> /// Inverts the meaning of the LDAP filter. /// </summary> /// <returns>a filter that contains a Not LDAP filter.</returns> public LdapFilter Not() { if (_filter.Contains("(")) { // This is a complex filter, enclose with parentheses return new LdapFilter($"(!({_filter}))"); } // This is a simple filter, no need to use parentheses unless it is a bitwise filter // Bitwise filter: attributename:ruleOID:=value return _filter.Contains(":=") ? new LdapFilter($"(!({_filter}))") : new LdapFilter($"(!{_filter})"); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="attributeType">The attribute of the filter.</param> /// <param name="filterType">The type of the filter.</param> /// <param name="attributeValue">The value of the filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or(string attributeType, string filterType, string attributeValue) { return Or(new LdapFilter(attributeType, filterType, attributeValue), false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="attributeType">The attribute of the filter.</param> /// <param name="filterType">The type of the filter.</param> /// <param name="attributeValue">The value of the filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or( string attributeType, string filterType, string attributeValue, bool appendFilter) { return Or(new LdapFilter(attributeType, filterType, attributeValue), appendFilter); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or(string ldapFilter) { return Or(ldapFilter, false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or(string ldapFilter, bool appendFilter) { Check.NotEmpty(ldapFilter, nameof(ldapFilter)); return appendFilter ? new LdapFilter($"(|({_filter})({Strip(ldapFilter)}))") : new LdapFilter($"(|({Strip(ldapFilter)})({_filter}))"); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or(LdapFilter ldapFilter) { return Or(Check.NotNull(ldapFilter, nameof(ldapFilter)).ToString(), false); } /// <summary> /// Combine the existing LDAP filter with the specified LDAP filter to create a new Or LDAP Filter. /// </summary> /// <param name="ldapFilter">A LDAP Filter.</param> /// <param name="appendFilter">if set to <c>true</c> append the filter.</param> /// <returns>a filter that contains an Or LDAP Filter.</returns> public LdapFilter Or(LdapFilter ldapFilter, bool appendFilter) { return Or(Check.NotNull(ldapFilter, nameof(ldapFilter)).ToString(), appendFilter); } /// <summary> /// Returns a <see cref="string" /> that represents the current <see cref="object" />. /// </summary> /// <returns>A <see cref="string" /> that represents the current <see cref="object" />.</returns> public override string ToString() { return $"({_filter})"; } private static string Strip(string ldapFilter) { var returnFilter = ldapFilter; if (returnFilter.StartsWith("(", StringComparison.InvariantCulture)) { returnFilter = returnFilter.Substring(1); } if (returnFilter.EndsWith(")", StringComparison.InvariantCulture)) { returnFilter = returnFilter.Substring(0, returnFilter.Length - 1); } return returnFilter; } } }
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> /// A matrix of type long with 3 columns and 3 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct lmat3 : IReadOnlyList<long>, IEquatable<lmat3> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public long m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public long m01; /// <summary> /// Column 0, Rows 2 /// </summary> [DataMember] public long m02; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public long m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public long m11; /// <summary> /// Column 1, Rows 2 /// </summary> [DataMember] public long m12; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public long m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public long m21; /// <summary> /// Column 2, Rows 2 /// </summary> [DataMember] public long m22; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public lmat3(long m00, long m01, long m02, long m10, long m11, long m12, long m20, long m21, long m22) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m22; } /// <summary> /// Constructs this matrix from a lmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m20 = 0; this.m21 = 0; this.m22 = 1; } /// <summary> /// Constructs this matrix from a lmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m20 = m.m20; this.m21 = m.m21; this.m22 = 1; } /// <summary> /// Constructs this matrix from a lmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m20 = m.m20; this.m21 = m.m21; this.m22 = 1; } /// <summary> /// Constructs this matrix from a lmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = 0; this.m21 = 0; this.m22 = 1; } /// <summary> /// Constructs this matrix from a lmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a lmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a lmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = 0; this.m21 = 0; this.m22 = 1; } /// <summary> /// Constructs this matrix from a lmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a lmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lvec2 c0, lvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0; this.m20 = 0; this.m21 = 0; this.m22 = 1; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lvec2 c0, lvec2 c1, lvec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0; this.m20 = c2.x; this.m21 = c2.y; this.m22 = 1; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lvec3 c0, lvec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = 0; this.m21 = 0; this.m22 = 1; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat3(lvec3 c0, lvec3 c1, lvec3 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public long[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public long[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public lvec3 Column0 { get { return new lvec3(m00, m01, m02); } set { m00 = value.x; m01 = value.y; m02 = value.z; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public lvec3 Column1 { get { return new lvec3(m10, m11, m12); } set { m10 = value.x; m11 = value.y; m12 = value.z; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public lvec3 Column2 { get { return new lvec3(m20, m21, m22); } set { m20 = value.x; m21 = value.y; m22 = value.z; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public lvec3 Row0 { get { return new lvec3(m00, m10, m20); } set { m00 = value.x; m10 = value.y; m20 = value.z; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public lvec3 Row1 { get { return new lvec3(m01, m11, m21); } set { m01 = value.x; m11 = value.y; m21 = value.z; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public lvec3 Row2 { get { return new lvec3(m02, m12, m22); } set { m02 = value.x; m12 = value.y; m22 = value.z; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static lmat3 Zero { get; } = new lmat3(0, 0, 0, 0, 0, 0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static lmat3 Ones { get; } = new lmat3(1, 1, 1, 1, 1, 1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static lmat3 Identity { get; } = new lmat3(1, 0, 0, 0, 1, 0, 0, 0, 1); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static lmat3 AllMaxValue { get; } = new lmat3(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static lmat3 DiagonalMaxValue { get; } = new lmat3(long.MaxValue, 0, 0, 0, long.MaxValue, 0, 0, 0, long.MaxValue); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static lmat3 AllMinValue { get; } = new lmat3(long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static lmat3 DiagonalMinValue { get; } = new lmat3(long.MinValue, 0, 0, 0, long.MinValue, 0, 0, 0, long.MinValue); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<long> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m10; yield return m11; yield return m12; yield return m20; yield return m21; yield return m22; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (3 x 3 = 9). /// </summary> public int Count => 9; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public long this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m10; case 4: return m11; case 5: return m12; case 6: return m20; case 7: return m21; case 8: return m22; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m10 = value; break; case 4: this.m11 = value; break; case 5: this.m12 = value; break; case 6: this.m20 = value; break; case 7: this.m21 = value; break; case 8: this.m22 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public long this[int col, int row] { get { return this[col * 3 + row]; } set { this[col * 3 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(lmat3 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m12.Equals(rhs.m12) && m20.Equals(rhs.m20)) && (m21.Equals(rhs.m21) && m22.Equals(rhs.m22)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is lmat3 && Equals((lmat3) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(lmat3 lhs, lmat3 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(lmat3 lhs, lmat3 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m22.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public lmat3 Transposed => new lmat3(m00, m10, m20, m01, m11, m21, m02, m12, m22); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public long MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12), m20), m21), m22); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public long MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12), m20), m21), m22); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => ((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22))); /// <summary> /// Returns the sum of all fields. /// </summary> public long Sum => ((((m00 + m01) + m02) + (m10 + m11)) + ((m12 + m20) + (m21 + m22))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => ((((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m02)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m12) + Math.Abs(m20)) + (Math.Abs(m21) + Math.Abs(m22)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public long NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m22)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m02), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m20), p)) + (Math.Pow((double)Math.Abs(m21), p) + Math.Pow((double)Math.Abs(m22), p)))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public long Determinant => m00 * (m11 * m22 - m21 * m12) - m10 * (m01 * m22 - m21 * m02) + m20 * (m01 * m12 - m11 * m02); /// <summary> /// Returns the adjunct of this matrix. /// </summary> public lmat3 Adjugate => new lmat3(m11 * m22 - m21 * m12, -m01 * m22 + m21 * m02, m01 * m12 - m11 * m02, -m10 * m22 + m20 * m12, m00 * m22 - m20 * m02, -m00 * m12 + m10 * m02, m10 * m21 - m20 * m11, -m00 * m21 + m20 * m01, m00 * m11 - m10 * m01); /// <summary> /// Returns the inverse of this matrix (use with caution). /// </summary> public lmat3 Inverse => Adjugate / Determinant; /// <summary> /// Executes a matrix-matrix-multiplication lmat3 * lmat2x3 -> lmat2x3. /// </summary> public static lmat2x3 operator*(lmat3 lhs, lmat2x3 rhs) => new lmat2x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12)); /// <summary> /// Executes a matrix-matrix-multiplication lmat3 * lmat3 -> lmat3. /// </summary> public static lmat3 operator*(lmat3 lhs, lmat3 rhs) => new lmat3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22)); /// <summary> /// Executes a matrix-matrix-multiplication lmat3 * lmat4x3 -> lmat4x3. /// </summary> public static lmat4x3 operator*(lmat3 lhs, lmat4x3 rhs) => new lmat4x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32), ((lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31) + lhs.m22 * rhs.m32)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static lvec3 operator*(lmat3 m, lvec3 v) => new lvec3(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z), ((m.m02 * v.x + m.m12 * v.y) + m.m22 * v.z)); /// <summary> /// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution). /// </summary> public static lmat3 operator/(lmat3 A, lmat3 B) => A * B.Inverse; /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static lmat3 CompMul(lmat3 A, lmat3 B) => new lmat3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m20 * B.m20, A.m21 * B.m21, A.m22 * B.m22); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static lmat3 CompDiv(lmat3 A, lmat3 B) => new lmat3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m20 / B.m20, A.m21 / B.m21, A.m22 / B.m22); /// <summary> /// Executes a component-wise + (add). /// </summary> public static lmat3 CompAdd(lmat3 A, lmat3 B) => new lmat3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m20 + B.m20, A.m21 + B.m21, A.m22 + B.m22); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static lmat3 CompSub(lmat3 A, lmat3 B) => new lmat3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m20 - B.m20, A.m21 - B.m21, A.m22 - B.m22); /// <summary> /// Executes a component-wise + (add). /// </summary> public static lmat3 operator+(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m22 + rhs.m22); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static lmat3 operator+(lmat3 lhs, long rhs) => new lmat3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m22 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static lmat3 operator+(long lhs, lmat3 rhs) => new lmat3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m22); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static lmat3 operator-(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m22 - rhs.m22); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static lmat3 operator-(lmat3 lhs, long rhs) => new lmat3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m22 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static lmat3 operator-(long lhs, lmat3 rhs) => new lmat3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m22); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static lmat3 operator/(lmat3 lhs, long rhs) => new lmat3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m22 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static lmat3 operator/(long lhs, lmat3 rhs) => new lmat3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m22); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static lmat3 operator*(lmat3 lhs, long rhs) => new lmat3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m22 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static lmat3 operator*(long lhs, lmat3 rhs) => new lmat3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m22); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static lmat3 operator%(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12, lhs.m20 % rhs.m20, lhs.m21 % rhs.m21, lhs.m22 % rhs.m22); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static lmat3 operator%(lmat3 lhs, long rhs) => new lmat3(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs, lhs.m20 % rhs, lhs.m21 % rhs, lhs.m22 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static lmat3 operator%(long lhs, lmat3 rhs) => new lmat3(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12, lhs % rhs.m20, lhs % rhs.m21, lhs % rhs.m22); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static lmat3 operator^(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12, lhs.m20 ^ rhs.m20, lhs.m21 ^ rhs.m21, lhs.m22 ^ rhs.m22); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static lmat3 operator^(lmat3 lhs, long rhs) => new lmat3(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs, lhs.m20 ^ rhs, lhs.m21 ^ rhs, lhs.m22 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static lmat3 operator^(long lhs, lmat3 rhs) => new lmat3(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12, lhs ^ rhs.m20, lhs ^ rhs.m21, lhs ^ rhs.m22); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static lmat3 operator|(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12, lhs.m20 | rhs.m20, lhs.m21 | rhs.m21, lhs.m22 | rhs.m22); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static lmat3 operator|(lmat3 lhs, long rhs) => new lmat3(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs, lhs.m20 | rhs, lhs.m21 | rhs, lhs.m22 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static lmat3 operator|(long lhs, lmat3 rhs) => new lmat3(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12, lhs | rhs.m20, lhs | rhs.m21, lhs | rhs.m22); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static lmat3 operator&(lmat3 lhs, lmat3 rhs) => new lmat3(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12, lhs.m20 & rhs.m20, lhs.m21 & rhs.m21, lhs.m22 & rhs.m22); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static lmat3 operator&(lmat3 lhs, long rhs) => new lmat3(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs, lhs.m20 & rhs, lhs.m21 & rhs, lhs.m22 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static lmat3 operator&(long lhs, lmat3 rhs) => new lmat3(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12, lhs & rhs.m20, lhs & rhs.m21, lhs & rhs.m22); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static lmat3 operator<<(lmat3 lhs, int rhs) => new lmat3(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs, lhs.m20 << rhs, lhs.m21 << rhs, lhs.m22 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static lmat3 operator>>(lmat3 lhs, int rhs) => new lmat3(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs, lhs.m20 >> rhs, lhs.m21 >> rhs, lhs.m22 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat3 operator<(lmat3 lhs, lmat3 rhs) => new bmat3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m22 < rhs.m22); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat3 operator<(lmat3 lhs, long rhs) => new bmat3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m22 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat3 operator<(long lhs, lmat3 rhs) => new bmat3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m22); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat3 operator<=(lmat3 lhs, lmat3 rhs) => new bmat3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m22 <= rhs.m22); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat3 operator<=(lmat3 lhs, long rhs) => new bmat3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m22 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat3 operator<=(long lhs, lmat3 rhs) => new bmat3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m22); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat3 operator>(lmat3 lhs, lmat3 rhs) => new bmat3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m22 > rhs.m22); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat3 operator>(lmat3 lhs, long rhs) => new bmat3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m22 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat3 operator>(long lhs, lmat3 rhs) => new bmat3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m22); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat3 operator>=(lmat3 lhs, lmat3 rhs) => new bmat3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m22 >= rhs.m22); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat3 operator>=(lmat3 lhs, long rhs) => new bmat3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m22 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat3 operator>=(long lhs, lmat3 rhs) => new bmat3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m22); } }
// 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.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class PropertiesShouldNotBeWriteOnlyTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new PropertiesShouldNotBeWriteOnlyAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new PropertiesShouldNotBeWriteOnlyAnalyzer(); } // Valid C# Tests that should not be flagged based on CA1044 (good tests) [Fact] public void CS_CA1044Good_Read_Write() { var code = @" using System; namespace CS_DesignLibrary { public class CS_GoodClassWithReadWriteProperty { string CS_someName; public string CS_Name { get { return CS_someName; } set { CS_someName = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_Read_Write1() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests1 { public class CS_GoodClassWithReadWriteProperty { protected string CS_field; public virtual string CS_ReadableProperty1 { get { return CS_field; } set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_public_Read_private_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests2 { public class CS_ClassWithReadableProperty { protected string CS_field; public string CS_AccessibleProperty2 { get { return CS_field; } private set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_protected_Read_private_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests3 { public class CS_ClassWithReadableProperty { protected string CS_field; protected string CS_AccessibleProperty3 { get { return CS_field; } private set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_internal_Read_private_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests4 { public class CS_GoodClassWithReadWriteProperty { protected string CS_field; internal string CS_AccessibleProperty4 { get { return CS_field; } private set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_protected_internal_Read_internal_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests5 { public class CS_GoodClassWithReadWriteProperty { protected string CS_field; protected internal string AccessibleProperty5 { get { return CS_field; } internal set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_public_Read_internal_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests6 { public class CS_GoodClassWithReadWriteProperty { protected string CS_field; public string CS_AccessibleProperty6 { get { return CS_field; } internal set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_public_Read_protected_Write() { var code = @" using System; namespace CS__GoodPropertiesShouldNotBeWriteOnlyTests7 { public class CS_GoodClassWithReadWriteProperty { protected string CS_field; public string CS_AccessibleProperty7 { get { return CS_field; } protected set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Good_public_override_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests8 { public class CS_ClassWithReadableProperty { public virtual string CS_ReadableProperty8 { get; set; } } public class CS_DerivedClassWithReadableProperty : CS_ClassWithReadableProperty { protected string CS_field; public override string CS_ReadableProperty8 { set { CS_field = value; } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Interface() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests9 { public interface IInterface { string InterfaceProperty { get; set; } } public class Class1 : IInterface { string IInterface.InterfaceProperty { get { throw new NotImplementedException(); } set { } } } }"; VerifyCSharp(code); } [Fact] public void CS_CA1044Base_Write() { var code = @" using System; namespace CS_GoodPropertiesShouldNotBeWriteOnlyTests10 { public class Base { public virtual string BaseProperty { get { throw new NotImplementedException(); } set { } } } public class Derived : Base { public override string BaseProperty { set { base.BaseProperty = value; } } } }"; VerifyCSharp(code); } // Valid VB Tests that should not be flagged based on CA1044 (good tests) [Fact] public void VB_CA1044Good_Read_Write() { var code = @" Imports System Namespace VB_DesignLibrary Public Class VB_GoodClassWithReadWriteProperty Private VB_someName As String Public Property VB_Name() As String Get Return VB_someName End Get Set(ByVal value As String) VB_someName = Value End Set End Property End Class End Namespace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_Read_Write1() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests1 Public Class VB_GoodClassWithReadWriteProperty Protected VB_field As String Public Overridable Property VB_ReadableProperty1() As String Get Return VB_field End Get Set(ByVal value As String) VB_field = Value End Set End Property End Class End Namespace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_public_Read_private_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests2 Public class VB_ClassWithReadableProperty Protected VB_field As String Public Property VB_AccessibleProperty2() As String Get Return VB_field End Get Private Set(ByVal value As String) VB_field = Value End Set End Property End Class End NameSpace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_protected_Read_private_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests3 Public class VB_ClassWithReadableProperty Protected VB_field As String Protected Property VB_AccessibleProperty3() As String Get Return VB_field End Get Private Set(ByVal value As String) VB_field = Value End Set End Property End Class End NameSpace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_internal_Read_private_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests4 Public Class ClassWithReadableProperty Protected VB_field As String Friend Property VB_AccessibleProperty4() As String Get Return VB_field End Get Private Set(ByVal value As String) VB_field = Value End Set End Property End Class End NameSpace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_protected_internal_Read_internal_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests5 Public class VB_ClassWithReadableProperty Protected VB_field As String Protected Friend Property AccessibleProperty5() As String Get Return VB_field End Get Friend Set(ByVal value As String) VB_field = value End Set End Property End Class End NameSpace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_public_Read_internal_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests6 Public class VB_ClassWithReadableProperty Protected VB_field As String Public Property VB_AccessibleProperty6() As String Get Return VB_field End Get Friend Set(ByVal value As String) VB_field = Value End Set End Property End Class End NameSpace "; VerifyBasic(code); } [Fact] public void VB_CA1044Good_public_Read_protected_Write() { var code = @" Imports System Namespace VB_GoodPropertiesShouldNotBeWriteOnlyTests7 Public class VB_ClassWithReadableProperty Protected VB_field As String Public Property VB_AccessibleProperty7() As String Get Return VB_field End Get Protected Set(ByVal value As String) VB_field = Value End Set End Property End Class End NameSpace "; VerifyBasic(code); } // C# Tests that should be flagged with CA1044 Addgetter [Fact] public void CS_CA1044Bad_Write_with_NoRead() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests { public class CS_BadClassWithWriteOnlyProperty { protected string CS_someName; public string CS_WriteOnlyProperty { set { CS_someName = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 23, CA1044MessageAddGetter, "CS_WriteOnlyProperty")); } [Fact] public void CS_CA1044Bad_Write_with_NoRead1() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests1 { public class CS_BadClassWithWriteOnlyProperty { protected string CS_someName; public string CS_WriteOnlyProperty1 { set { CS_someName = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 23, CA1044MessageAddGetter, "CS_WriteOnlyProperty1")); } [Fact] public void CS_CA1044Bad_Write_with_NoRead2() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests2 { public class CS_BadClassWithWriteOnlyProperty { string CS_someName; protected string CS_WriteOnlyProperty2 { set { CS_someName = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 26, CA1044MessageAddGetter, "CS_WriteOnlyProperty2")); } [Fact] public void CS_CA1044Bad_Write_with_NoRead3() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests3 { public class CS_BadClassWithWriteOnlyProperty { protected string CS_someName; protected string CS_WriteOnlyProperty3 { set { CS_someName = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 26, CA1044MessageAddGetter, "CS_WriteOnlyProperty3")); } [Fact] public void CS_CA1044Bad_Write_with_NoRead4() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests4 { public class CS_BadClassWithWriteOnlyProperty { protected string CS_someName; protected internal string CS_WriteOnlyProperty4 { set { CS_someName = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 35, CA1044MessageAddGetter, "CS_WriteOnlyProperty4")); } [Fact] public void CS_CA1044bad_Base_Write() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests5 { public class CS_Base { public virtual string CS_BaseProperty5 { set { } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(7, 31, CA1044MessageAddGetter, "CS_BaseProperty5")); } [Fact] public void CS_CA1044bad_Interface_Write() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests6 { public interface CS_IInterface { string CS_InterfaceProperty6 { set; } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(7, 16, CA1044MessageAddGetter, "CS_InterfaceProperty6")); } // C# Tests that should be flagged with CA1044 MakeMoreAccessible [Fact] public void CS_CA1044Bad_InaccessibleRead() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests { public class CS_BadClassWithWriteOnlyProperty { string field; public string CS_InaccessibleProperty { private get { return field; } set { field = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 24, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty")); } [Fact] public void CS_CA1044Bad_InaccessibleRead1() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests1 { public class CS_BadClassWithWriteOnlyProperty { string field; protected string CS_InaccessibleProperty1 { private get { return field; } set { field = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 26, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty1")); } [Fact] public void CS_CA1044Bad_InaccessibleRead2() { var code = @" using System; namespace CS_BadPropertiesShouldNotBeWriteOnlyTests2 { public class CS_BadClassWithWriteOnlyProperty { protected string field; protected internal string CS_InaccessibleProperty2 { internal get { return field; } set { field = value; } } } }"; VerifyCSharp(code, GetCA1044CSharpResultAt(8, 35, CA1044MessageMakeMoreAccessible, "CS_InaccessibleProperty2")); } // VB Tests that should be flagged with CA1044 Addgetter [Fact] public void VB_CA1044Bad_Write_with_NoRead() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Public WriteOnly Property VB_WriteOnlyProperty As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 35, CA1044MessageAddGetter, "VB_WriteOnlyProperty")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead1() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests1 Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Protected WriteOnly Property VB_WriteOnlyProperty1() As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 38, CA1044MessageAddGetter, "VB_WriteOnlyProperty1")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead2() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Public WriteOnly Property VB_WriteOnlyProperty2 As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 35, CA1044MessageAddGetter, "VB_WriteOnlyProperty2")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead3() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests3 Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Protected Friend WriteOnly Property VB_WriteOnlyProperty3() As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 45, CA1044MessageAddGetter, "VB_WriteOnlyProperty3")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead4() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests4 Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Public WriteOnly Property VB_WriteOnlyProperty4() As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 35, CA1044MessageAddGetter, "VB_WriteOnlyProperty4")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead5() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests5 Public Class VB_BadClassWithWriteOnlyProperty Protected VB_someName As String Public WriteOnly Property VB_WriteOnlyProperty5() As String Set(ByVal value As String) VB_someName = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 35, CA1044MessageAddGetter, "VB_WriteOnlyProperty5")); } [Fact] public void VB_CA1044Bad_Interface_Write() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests Public Interface IInterface WriteOnly Property InterfaceProperty As String End Interface Public Class Class1 Implements IInterface Private WriteOnly Property IInterface_InterfaceProperty As String Implements IInterface.InterfaceProperty Set(ByVal value As String) End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(5, 28, CA1044MessageAddGetter, "InterfaceProperty")); } [Fact] public void VB_CA1044Bad_Interface_Write1() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests1 Public Interface VB_IInterface WriteOnly Property VB_InterfaceProperty1() As String End Interface End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(5, 28, CA1044MessageAddGetter, "VB_InterfaceProperty1")); } [Fact] public void VB_CA1044Bad_Write_with_NoRead6() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests5 Public Interface IInterface WriteOnly Property InterfaceProperty As String End Interface Public Class Class1 Implements IInterface Private WriteOnly Property IInterface_InterfaceProperty As String Implements IInterface.InterfaceProperty Set(ByVal value As String) End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(5, 28, CA1044MessageAddGetter, "InterfaceProperty")); } [Fact] public void VB_CA1044Bad_Base_Write() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests Public Class VB_Base Public Overridable WriteOnly Property VB_BaseProperty() As String Set(ByVal value As String) End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(5, 47, CA1044MessageAddGetter, "VB_BaseProperty")); } // VB Tests that should be flagged with CA1044 MakeMoreAccessible [Fact] public void VB_CA1044Bad_InaccessibleRead() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests Public Class VB_BadClassWithWriteOnlyProperty Private field As String Public Property VB_InaccessibleProperty As String Private Get Return field End Get Set(ByVal value As String) field = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 25, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty")); } [Fact] public void VB_CA1044Bad_InaccessibleRead1() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests1 Public Class VB_BadClassWithWriteOnlyProperty Private field As String Protected Property VB_InaccessibleProperty1() As String Private Get Return field End Get Set(ByVal value As String) field = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 28, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty1")); } [Fact] public void VB_CA1044Bad_InaccessibleRead2() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests2 Public Class VB_BadClassWithWriteOnlyProperty Private field As String Protected Friend Property VB_InaccessibleProperty2() As String Friend Get Return field End Get Set(ByVal value As String) field = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 35, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty2")); } [Fact] public void VB_CA1044Bad_InaccessibleRead3() { var code = @" Imports System Namespace VB_BadPropertiesShouldNotBeWriteOnlyTests3 Public Class VB_BadClassWithWriteOnlyProperty Private field As String Public Property VB_InaccessibleProperty3() As String Friend Get Return field End Get Set(ByVal value As String) field = value End Set End Property End Class End NameSpace "; VerifyBasic(code, GetCA1044BasicResultAt(6, 25, CA1044MessageMakeMoreAccessible, "VB_InaccessibleProperty3")); } private static readonly string CA1044MessageAddGetter = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageAddGetter; private static readonly string CA1044MessageMakeMoreAccessible = MicrosoftApiDesignGuidelinesAnalyzersResources.PropertiesShouldNotBeWriteOnlyMessageMakeMoreAccessible; private static DiagnosticResult GetCA1044CSharpResultAt(int line, int column, string CA1044Message, string objectName) { return GetCSharpResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName)); } private static DiagnosticResult GetCA1044BasicResultAt(int line, int column, string CA1044Message, string objectName) { return GetBasicResultAt(line, column, PropertiesShouldNotBeWriteOnlyAnalyzer.RuleId, string.Format(CA1044Message, objectName)); } } }
// // System.Web.UI.WebControls.BoundColumn.cs // // Authors: // Gaurav Vaish (gvaish@iitk.ac.in) // Andreas Nahr (ClassDevelopment@A-SoftTech.com) // // (C) Gaurav Vaish (2002) // (C) 2003 Andreas Nahr // // // 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.ComponentModel; using System.Web; using System.Web.UI; namespace System.Web.UI.WebControls { public class BoundColumn : DataGridColumn { public static readonly string thisExpr = "!"; private bool boundFieldDescriptionValid; private string boundField; private string formatting; private PropertyDescriptor desc; public BoundColumn(): base() { } public override void Initialize() { base.Initialize(); desc = null; boundField = DataField; formatting = DataFormatString; boundFieldDescriptionValid = false; } public override void InitializeCell(TableCell cell, int columnIndex, ListItemType itemType) { base.InitializeCell(cell, columnIndex, itemType); Control bindCtrl = null; Control toAdd = null; switch(itemType) { case ListItemType.Item : goto case ListItemType.SelectedItem; case ListItemType.AlternatingItem : goto case ListItemType.SelectedItem; case ListItemType.SelectedItem : if(DataField.Length != 0) bindCtrl = cell; break; case ListItemType.EditItem : if(!ReadOnly) { TextBox box = new TextBox(); toAdd = box; if(DataField.Length != 0) bindCtrl = box; } else goto case ListItemType.SelectedItem; break; } if(toAdd != null) cell.Controls.Add(toAdd); if(bindCtrl != null) bindCtrl.DataBinding += new EventHandler(OnDataBindColumn); //throw new NotImplementedException(); } private void OnDataBindColumn(object sender, EventArgs e) { Control senderCtrl = (Control)sender; DataGridItem item = (DataGridItem)senderCtrl.NamingContainer; object data = item.DataItem; if(!boundFieldDescriptionValid) { if(boundField != BoundColumn.thisExpr) { desc = TypeDescriptor.GetProperties(data).Find(boundField, true); if(desc == null && !DesignMode) { throw new HttpException( HttpRuntime.FormatResourceString("File_Not_Found", boundField)); } boundFieldDescriptionValid = true; } } object value = data; string val = String.Empty; if(desc == null && DesignMode) { throw new NotImplementedException(); } else { if(desc != null) value = desc.GetValue(data); val = FormatDataValue(value); } if(senderCtrl is TableCell) { if(val.Length == 0) val = "&nbsp;"; ((TableCell)senderCtrl).Text = val; } else { ((TextBox)senderCtrl).Text = val; } } [DefaultValue (""), WebCategory ("Misc")] [WebSysDescription ("The field that this column is bound to.")] public virtual string DataField { get { object o = ViewState["DataField"]; if(o != null) return (string)o; return String.Empty; } set { ViewState["DataField"] = value; OnColumnChanged(); } } [DefaultValue (""), WebCategory ("Misc")] [WebSysDescription ("A format string that is applied to the data value.")] public virtual string DataFormatString { get { object o = ViewState["DataFormatString"]; if(o != null) return (string)o; return String.Empty; } set { ViewState["DataFormatString"] = value; OnColumnChanged(); } } [DefaultValue (false), WebCategory ("Misc")] [WebSysDescription ("Determines if the databound field can only be displayed or also edited.")] public virtual bool ReadOnly { get { object o = ViewState["ReadOnly"]; if(o != null) return (bool)o; return false; } set { ViewState["ReadOnly"] = value; } } protected virtual string FormatDataValue(Object dataValue) { string retVal = String.Empty; if(dataValue != null) { if(formatting.Length == 0) retVal = dataValue.ToString(); else retVal = String.Format(formatting, dataValue); } return retVal; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace ClearScript.Installer.DemoWeb.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 System.Collections; using System.Diagnostics; using System.IO.PortsTests; using System.Text; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class DiscardNull_Property : PortsTest { //The default number of bytes to read/write to verify the DiscardNull private const int DEFAULT_NUM_CHARS_TO_WRITE = 8; //The default number of null characters to be inserted into the characters written private const int DEFUALT_NUM_NULL_CHAR = 1; //The default number of chars to write with when testing timeout with Read(char[], int, int) private const int DEFAULT_READ_CHAR_ARRAY_SIZE = 8; //The default number of bytes to write with when testing timeout with Read(byte[], int, int) private const int DEFAULT_READ_BYTE_ARRAY_SIZE = 8; private delegate char[] ReadMethodDelegate(SerialPort com); #region Test Cases [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_Read_byte_int_int() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, Read_byte_int_int, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_Read_char_int_int() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, Read_char_int_int, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_ReadByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with ReadByte"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, ReadByte, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_ReadChar() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with ReadChar"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, ReadChar, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_ReadLine() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with ReadLine"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, ReadLine, true); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_Default_ReadTo() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with ReadTo"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, ReadTo, true); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_Read_byte_int_int_Before() { Debug.WriteLine("Verifying true DiscardNull with Read_byte_int_int before open"); VerifyDiscardNullBeforeOpen(true, Read_byte_int_int, false); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_Read_char_int_int_After() { Debug.WriteLine("Verifying true DiscardNull with Read_char_int_int after open"); VerifyDiscardNullAfterOpen(true, Read_char_int_int, false); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_ReadByte_Before() { Debug.WriteLine("Verifying true DiscardNull with ReadByte before open"); VerifyDiscardNullBeforeOpen(true, ReadByte, false); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_ReadChar_After() { Debug.WriteLine("Verifying true DiscardNull with ReadChar after open"); VerifyDiscardNullAfterOpen(true, ReadChar, false); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_ReadLine_Before() { Debug.WriteLine("Verifying true DiscardNull with ReadLine before open"); VerifyDiscardNullBeforeOpen(true, ReadLine, true); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_ReadTo_After() { Debug.WriteLine("Verifying true DiscardNull with ReadTo after open"); VerifyDiscardNullAfterOpen(true, ReadTo, true); } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_false_Read_byte_int_int_Before() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with Read_byte_int_int"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com1.DiscardNull = true; com1.DiscardNull = false; serPortProp.SetProperty("DiscardNull", false); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, Read_byte_int_int, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_true_true_Read_char_int_int_After() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with Read_char_int_int"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com1.DiscardNull = true; com1.DiscardNull = true; serPortProp.SetProperty("DiscardNull", true); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, Read_char_int_int, false); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void DiscardNull_false_flase_Default_ReadByte() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default DiscardNull with ReadByte"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com1.DiscardNull = false; com1.DiscardNull = false; serPortProp.SetProperty("DiscardNull", false); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, ReadByte, false); serPortProp.VerifyPropertiesAndPrint(com1); } } #endregion #region Verification for Test Cases private void VerifyDiscardNullBeforeOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.DiscardNull = discardNull; com1.Open(); serPortProp.SetProperty("DiscardNull", discardNull); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, readMethod, sendNewLine); serPortProp.VerifyPropertiesAndPrint(com1); } } private void VerifyDiscardNullAfterOpen(bool discardNull, ReadMethodDelegate readMethod, bool sendNewLine) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com1.DiscardNull = discardNull; serPortProp.SetProperty("DiscardNull", discardNull); serPortProp.VerifyPropertiesAndPrint(com1); VerifyDiscardNull(com1, readMethod, sendNewLine); serPortProp.VerifyPropertiesAndPrint(com1); } } private void VerifyDiscardNull(SerialPort com1, ReadMethodDelegate readMethod, bool sendNewLine) { using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { char[] expectedChars; char[] rcvChars; int origReadTimeout; char[] xmitChars = new char[DEFAULT_NUM_CHARS_TO_WRITE]; byte[] xmitBytes; byte[] expectedBytes; Random rndGen = new Random(); int numNulls = 0; int expectedIndex; origReadTimeout = com1.ReadTimeout; //Generate some random chars to transfer for (int i = 0; i < xmitChars.Length; i++) { //xmitChars[i] = (char)rndGen.Next(1, UInt16.MaxValue); xmitChars[i] = (char)rndGen.Next(60, 80); } //Inject the null char randomly for (int i = 0; i < DEFUALT_NUM_NULL_CHAR; i++) { int nullIndex = rndGen.Next(0, xmitChars.Length); if ('\0' != xmitChars[nullIndex]) { numNulls++; } xmitChars[nullIndex] = '\0'; } xmitBytes = com1.Encoding.GetBytes(xmitChars); if (com1.DiscardNull) { expectedIndex = 0; expectedChars = new char[xmitChars.Length - numNulls]; for (int i = 0; i < xmitChars.Length; i++) { if ('\0' != xmitChars[i]) { expectedChars[expectedIndex] = xmitChars[i]; expectedIndex++; } } } else { expectedChars = new char[xmitChars.Length]; Array.Copy(xmitChars, 0, expectedChars, 0, expectedChars.Length); } expectedBytes = com1.Encoding.GetBytes(expectedChars); expectedChars = com1.Encoding.GetChars(expectedBytes); com2.Open(); com2.Write(xmitBytes, 0, xmitBytes.Length); TCSupport.WaitForReadBufferToLoad(com1, expectedBytes.Length); if (sendNewLine) com2.WriteLine(""); com1.ReadTimeout = 250; rcvChars = readMethod(com1); Assert.Equal(0, com1.BytesToRead); Assert.Equal(expectedChars, rcvChars); com1.ReadTimeout = origReadTimeout; } } private char[] Read_byte_int_int(SerialPort com) { ArrayList receivedBytes = new ArrayList(); byte[] buffer = new byte[DEFAULT_READ_BYTE_ARRAY_SIZE]; int totalBytesRead = 0; int numBytes; while (true) { try { numBytes = com.Read(buffer, 0, buffer.Length); } catch (TimeoutException) { break; } receivedBytes.InsertRange(totalBytesRead, buffer); totalBytesRead += numBytes; } if (totalBytesRead < receivedBytes.Count) receivedBytes.RemoveRange(totalBytesRead, receivedBytes.Count - totalBytesRead); return com.Encoding.GetChars((byte[])receivedBytes.ToArray(typeof(byte))); } private char[] Read_char_int_int(SerialPort com) { ArrayList receivedChars = new ArrayList(); char[] buffer = new char[DEFAULT_READ_CHAR_ARRAY_SIZE]; int totalCharsRead = 0; int numChars; while (true) { try { numChars = com.Read(buffer, 0, buffer.Length); } catch (TimeoutException) { break; } receivedChars.InsertRange(totalCharsRead, buffer); totalCharsRead += numChars; } if (totalCharsRead < receivedChars.Count) receivedChars.RemoveRange(totalCharsRead, receivedChars.Count - totalCharsRead); return (char[])receivedChars.ToArray(typeof(char)); } private char[] ReadByte(SerialPort com) { ArrayList receivedBytes = new ArrayList(); int rcvByte; while (true) { try { rcvByte = com.ReadByte(); } catch (TimeoutException) { break; } receivedBytes.Add((byte)rcvByte); } return com.Encoding.GetChars((byte[])receivedBytes.ToArray(typeof(byte))); } private char[] ReadChar(SerialPort com) { ArrayList receivedChars = new ArrayList(); int rcvChar; while (true) { try { rcvChar = com.ReadChar(); } catch (TimeoutException) { break; } receivedChars.Add((char)rcvChar); } return (char[])receivedChars.ToArray(typeof(char)); } private char[] ReadLine(SerialPort com) { StringBuilder rcvStringBuilder = new StringBuilder(); string rcvString; while (true) { try { rcvString = com.ReadLine(); } catch (TimeoutException) { break; } rcvStringBuilder.Append(rcvString); } return rcvStringBuilder.ToString().ToCharArray(); } private char[] ReadTo(SerialPort com) { StringBuilder rcvStringBuilder = new StringBuilder(); string rcvString; while (true) { try { rcvString = com.ReadTo(com.NewLine); } catch (TimeoutException) { break; } rcvStringBuilder.Append(rcvString); } return rcvStringBuilder.ToString().ToCharArray(); } #endregion } }
using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; using System.Collections.Generic; namespace UIWidgets { /// <summary> /// Dialog. /// </summary> [AddComponentMenu("UI/UIWidgets/Dialog")] public class Dialog : MonoBehaviour, ITemplatable { [SerializeField] Button defaultButton; /// <summary> /// Gets or sets the default button. /// </summary> /// <value>The default button.</value> public Button DefaultButton { get { return defaultButton; } set { defaultButton = value; } } [SerializeField] Text titleText; /// <summary> /// Gets or sets the text component. /// </summary> /// <value>The text.</value> public Text TitleText { get { return titleText; } set { titleText = value; } } [SerializeField] Text contentText; /// <summary> /// Gets or sets the text component. /// </summary> /// <value>The text.</value> public Text ContentText { get { return contentText; } set { contentText = value; } } [SerializeField] Image dialogIcon; /// <summary> /// Gets or sets the icon component. /// </summary> /// <value>The icon.</value> public Image Icon { get { return dialogIcon; } set { dialogIcon = value; } } DialogInfoBase dialogInfo; /// <summary> /// Gets the dialog info. /// </summary> /// <value>The dialog info.</value> public DialogInfoBase DialogInfo { get { if (dialogInfo==null) { dialogInfo = GetComponent<DialogInfoBase>(); } return dialogInfo; } } bool isTemplate = true; /// <summary> /// Gets a value indicating whether this instance is template. /// </summary> /// <value><c>true</c> if this instance is template; otherwise, <c>false</c>.</value> public bool IsTemplate { get { return isTemplate; } set { isTemplate = value; } } /// <summary> /// Gets the name of the template. /// </summary> /// <value>The name of the template.</value> public string TemplateName { get; set; } static Templates<Dialog> templates; /// <summary> /// Dialog templates. /// </summary> public static Templates<Dialog> Templates { get { if (templates==null) { templates = new Templates<Dialog>(); } return templates; } set { templates = value; } } /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> protected virtual void Awake() { if (IsTemplate) { gameObject.SetActive(false); } } /// <summary> /// This function is called when the MonoBehaviour will be destroyed. /// </summary> protected virtual void OnDestroy() { DeactivateButtons(); if (!IsTemplate) { templates = null; return ; } //if FindTemplates never called than TemplateName==null if (TemplateName!=null) { Templates.Delete(TemplateName); } } /// <summary> /// Return dialog instance by the specified template name. /// </summary> /// <param name="template">Template name.</param> static public Dialog Template(string template) { return Templates.Instance(template); } /// <summary> /// Return Dialog instance using current instance as template. /// </summary> public Dialog Template() { if ((TemplateName!=null) && Templates.Exists(TemplateName)) { //do nothing } else if (!Templates.Exists(gameObject.name)) { Templates.Add(gameObject.name, this); } else if (Templates.Get(gameObject.name)!=this) { Templates.Add(gameObject.name, this); } return Templates.Instance(gameObject.name); } /// <summary> /// The modal key. /// </summary> protected int? ModalKey; /// <summary> /// Show dialog. /// </summary> /// <param name="title">Title.</param> /// <param name="message">Message.</param> /// <param name="buttons">Buttons.</param> /// <param name="focusButton">Set focus on button with specified name.</param> /// <param name="position">Position.</param> /// <param name="icon">Icon.</param> /// <param name="modal">If set to <c>true</c> modal.</param> /// <param name="modalSprite">Modal sprite.</param> /// <param name="modalColor">Modal color.</param> /// <param name="canvas">Canvas.</param> public virtual void Show(string title = null, string message = null, DialogActions buttons = null, string focusButton = null, Vector3? position = null, Sprite icon = null, bool modal = false, Sprite modalSprite = null, Color? modalColor = null, Canvas canvas = null) { if (position==null) { position = new Vector3(0, 0, 0); } SetInfo(title, message, icon); var parent = (canvas!=null) ? canvas.transform : Utilites.FindTopmostCanvas(gameObject.transform); if (parent!=null) { transform.SetParent(parent, false); } if (modal) { ModalKey = ModalHelper.Open(this, modalSprite, modalColor); } else { ModalKey = null; } transform.SetAsLastSibling(); transform.localPosition = (Vector3)position; gameObject.SetActive(true); CreateButtons(buttons, focusButton); } /// <summary> /// Sets the info. /// </summary> /// <param name="title">Title.</param> /// <param name="message">Message.</param> /// <param name="icon">Icon.</param> public virtual void SetInfo(string title=null, string message=null, Sprite icon=null) { if (DialogInfo!=null) { DialogInfo.SetInfo(title, message, icon); } else { if ((title!=null) && (TitleText!=null)) { TitleText.text = title; } if ((message!=null) && (ContentText!=null)) { ContentText.text = message; } if ((icon!=null) && (Icon!=null)) { Icon.sprite = icon; } } } /// <summary> /// Close dialog. /// </summary> public virtual void Hide() { if (ModalKey!=null) { ModalHelper.Close((int)ModalKey); } Return(); } /// <summary> /// The buttons cache. /// </summary> protected Stack<Button> buttonsCache = new Stack<Button>(); /// <summary> /// The buttons in use. /// </summary> protected Dictionary<string,Button> buttonsInUse = new Dictionary<string,Button>(); /// <summary> /// The buttons actions. /// </summary> protected Dictionary<string,UnityAction> buttonsActions = new Dictionary<string,UnityAction>(); /// <summary> /// Creates the buttons. /// </summary> /// <param name="buttons">Buttons.</param> /// <param name="focusButton">Focus button.</param> protected virtual void CreateButtons(DialogActions buttons, string focusButton) { defaultButton.gameObject.SetActive(false); if (buttons==null) { return ; } buttons.ForEach(x => { var button = GetButton(); UnityAction callback = () => { if (x.Value()) { Hide(); } }; buttonsInUse.Add(x.Key, button); buttonsActions.Add(x.Key, callback); button.gameObject.SetActive(true); button.transform.SetAsLastSibling(); var dialog_button = button.GetComponentInChildren<DialogButtonComponent>(); if (dialog_button!=null) { dialog_button.SetButtonName(x.Key); } else { var text = button.GetComponentInChildren<Text>(); if (text!=null) { text.text = x.Key; } } button.onClick.AddListener(buttonsActions[x.Key]); if (x.Key==focusButton) { button.Select(); } }); } /// <summary> /// Gets the button. /// </summary> /// <returns>The button.</returns> protected virtual Button GetButton() { if (buttonsCache.Count > 0) { return buttonsCache.Pop(); } var button = Instantiate(DefaultButton) as Button; button.transform.SetParent(DefaultButton.transform.parent, false); //Utilites.FixInstantiated(DefaultButton, button); return button; } /// <summary> /// Return this instance to cache. /// </summary> protected virtual void Return() { Templates.ToCache(this); DeactivateButtons(); ResetParametres(); } /// <summary> /// Deactivates the buttons. /// </summary> protected virtual void DeactivateButtons() { buttonsInUse.ForEach(DeactivateButton); buttonsInUse.Clear(); buttonsActions.Clear(); } /// <summary> /// Deactivates the button. /// </summary> /// <param name="button">Button.</param> protected virtual void DeactivateButton(KeyValuePair<string,Button> button) { button.Value.gameObject.SetActive(false); button.Value.onClick.RemoveListener(buttonsActions[button.Key]); buttonsCache.Push(button.Value); } /// <summary> /// Resets the parametres. /// </summary> protected virtual void ResetParametres() { var template = Templates.Get(TemplateName); var title = template.TitleText!=null ? template.TitleText.text : ""; var content = template.ContentText!=null ? template.ContentText.text : ""; var icon = template.Icon!=null ? template.Icon.sprite : null; SetInfo(title, content, icon); } /// <summary> /// Default function to close dialog. /// </summary> static public bool Close() { return true; } } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Text; #if logging #endif namespace Encog.Parse.Tags { /// <summary> /// HTMLTag: This class holds a single HTML tag. This class subclasses the /// AttributeList class. This allows the HTMLTag class to hold a collection of /// attributes, just as an actual HTML tag does. /// </summary> public class Tag { /// <summary> /// Tag types. /// </summary> public enum Type { /// <summary> /// A beginning tag. /// </summary> Begin, /// <summary> /// An ending tag. /// </summary> End, /// <summary> /// A comment. /// </summary> Comment, /// <summary> /// A CDATA section. /// </summary> CDATA } ; /// <summary> /// The tag's attributes. /// </summary> private readonly IDictionary<String, String> _attributes = new Dictionary<String, String>(); /// <summary> /// The tag name. /// </summary> private String _name = ""; /// <summary> /// The tag type. /// </summary> private Type _type; /// <summary> /// Clear the name, type and attributes. /// </summary> public void Clear() { _attributes.Clear(); _name = ""; _type = Type.Begin; } /// <summary> /// Clone this object. /// </summary> /// <returns>A cloned copy of the object.</returns> public virtual object Clone() { var result = new Tag {Name = Name, TagType = TagType}; foreach (String key in _attributes.Keys) { String value = _attributes[key]; result.Attributes[key] = value; } return result; } /// <summary> /// Get the specified attribute as an integer. /// </summary> /// <param name="attributeId">The attribute name.</param> /// <returns>The attribute value.</returns> public int GetAttributeInt(String attributeId) { try { String str = GetAttributeValue(attributeId); return int.Parse(str); } catch (Exception e) { #if logging if (logger.IsErrorEnabled) { logger.Error("Exception", e); } #endif throw new ParseError(e); } } /// <summary> /// The attributes for this tag as a dictionary. /// </summary> public IDictionary<String, String> Attributes { get { return _attributes; } } /// <summary> /// Get the value of the specified attribute. /// </summary> /// <param name="name">The name of an attribute.</param> /// <returns>The value of the specified attribute.</returns> public String GetAttributeValue(String name) { if (!_attributes.ContainsKey(name)) return null; return _attributes[name]; } /// <summary> /// The tag name. /// </summary> public String Name { get { return _name; } set { _name = value; } } /// <summary> /// The tag type. /// </summary> public Type TagType { get { return _type; } set { _type = value; } } /// <summary> /// Set a HTML attribute. /// </summary> /// <param name="name">The name of the attribute.</param> /// <param name="valueRen">The value of the attribute.</param> public void SetAttribute(String name, String valueRen) { _attributes[name] = valueRen; } /// <summary> /// Convert this tag back into string form, with the /// beginning &lt; and ending &gt;. /// </summary> /// <returns>The Attribute object that was found.</returns> public override String ToString() { var buffer = new StringBuilder("<"); if (_type == Type.End) { buffer.Append("/"); } buffer.Append(_name); ICollection<String> set = _attributes.Keys; foreach (String key in set) { String value = _attributes[key]; buffer.Append(' '); if (value == null) { buffer.Append("\""); buffer.Append(key); buffer.Append("\""); } else { buffer.Append(key); buffer.Append("=\""); buffer.Append(value); buffer.Append("\""); } } buffer.Append(">"); return buffer.ToString(); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.Presentation { using System.Collections; using System.Collections.Generic; using System.Runtime; using System.ComponentModel; using Microsoft.VisualBasic.Activities; using System.Activities.Presentation.View; using System.Activities.Expressions; using System.Reflection; using System.Collections.ObjectModel; class NamespaceListPropertyDescriptor : PropertyDescriptor { public const string ImportCollectionPropertyName = "Imports"; public const string AvailableNamespacesPropertyName = "AvailableNamespaces"; public const string NamespacePropertyName = "Namespace"; object instance; public NamespaceListPropertyDescriptor(object instance) : base(ImportCollectionPropertyName, null) { this.instance = instance; } public override Type ComponentType { get { return this.instance.GetType(); } } public override bool IsReadOnly { get { return true; } } public override Type PropertyType { get { return typeof(NamespaceList); } } public override bool IsBrowsable { get { return false; } } public override bool CanResetValue(object component) { return false; } public override object GetValue(object component) { VisualBasicSettings settings = VisualBasic.GetSettings(component); IList<AssemblyReference> references; IList<string> namespaces = NamespaceHelper.GetTextExpressionNamespaces(component, out references); if ((namespaces != null) && ((namespaces.Count > 0) || ((namespaces.Count == 0) && (settings == null)))) { return new TextExpressionNamespaceList(namespaces, references); } else { Fx.Assert(settings != null, "Either VB settings or new TextExpression attached properties should be set"); return new VisualBasicNamespaceList(settings.ImportReferences); } } public override void ResetValue(object component) { IList<AssemblyReference> references; IList<string> importedNamespaces = NamespaceHelper.GetTextExpressionNamespaces(component, out references); if (importedNamespaces != null) { NamespaceHelper.SetTextExpressionNamespaces(component, null, null); } else { NamespaceHelper.SetVisualBasicSettings(component, null); } } public override void SetValue(object component, object value) { NamespaceList namespaceList = value as NamespaceList; if (namespaceList != null) { if (namespaceList is VisualBasicNamespaceList) { VisualBasicNamespaceList visualBasicNamespaces = namespaceList as VisualBasicNamespaceList; VisualBasicSettings settings = new VisualBasicSettings(); settings.ImportReferences.UnionWith(visualBasicNamespaces.VisualBasicImports); NamespaceHelper.SetVisualBasicSettings(component, settings); } else { Fx.Assert(namespaceList is TextExpressionNamespaceList, "The namespace list must be either of VisualBaiscSettings or TextExpression attached properties."); TextExpressionNamespaceList textExpressionNamespace = namespaceList as TextExpressionNamespaceList; NamespaceHelper.SetTextExpressionNamespaces( component, textExpressionNamespace.TextExpressionNamespaces, textExpressionNamespace.TextExpressionReferences); } } else { this.ResetValue(component); } } public override bool ShouldSerializeValue(object component) { throw FxTrace.Exception.AsError(new NotSupportedException()); } protected override void FillAttributes(IList attributeList) { attributeList.Add(new BrowsableAttribute(false)); base.FillAttributes(attributeList); } } class NamespaceData { public string Namespace { get; set; } //Used by screen reader public override string ToString() { return this.Namespace; } } abstract class NamespaceList : IList { //list of uniqueNamespaces, the element is a tuple of the namespace and a arbitary data for consumer to use List<NamespaceData> uniqueNamespaces; Dictionary<string, List<string>> availableNamespaces; protected List<NamespaceData> UniqueNamespaces { get { if (this.uniqueNamespaces == null) { this.uniqueNamespaces = new List<NamespaceData>(); } return this.uniqueNamespaces; } } public Dictionary<string, List<string>> AvailableNamespaces { get { if (availableNamespaces == null) { availableNamespaces = new Dictionary<string, List<string>>(); } return availableNamespaces; } } internal int Lookup(string ns) { for (int i = 0; i < this.UniqueNamespaces.Count; i++) { if (this.UniqueNamespaces[i].Namespace == ns) { return i; } } return -1; } public int Add(object value) { NamespaceData ns = value as NamespaceData; if (ns == null) { throw FxTrace.Exception.AsError(new ArgumentException(SR.NamespaceListArgumentMustBeNamespaceData, "value")); } if (Lookup(ns.Namespace) == -1) { this.AddCore(ns); return ((IList)this.UniqueNamespaces).Add(ns); } else { return -1; } } public void Clear() { this.ClearCore(); this.UniqueNamespaces.Clear(); } public bool Contains(object value) { return ((IList)this.UniqueNamespaces).Contains(value); } public int IndexOf(object value) { return ((IList)this.UniqueNamespaces).IndexOf(value); } public void Insert(int index, object value) { NamespaceData ns = value as NamespaceData; if (ns == null) { throw FxTrace.Exception.AsError(new ArgumentException(SR.NamespaceListArgumentMustBeNamespaceData, "value")); } if (Lookup(ns.Namespace) == -1) { this.UniqueNamespaces.Insert(index, ns); this.InsertCore(index, ns); } else { throw FxTrace.Exception.AsError(new InvalidOperationException()); } } public bool IsFixedSize { get { return false; } } public bool IsReadOnly { get { return false; } } public void Remove(object value) { NamespaceData ns = value as NamespaceData; if (ns == null) { throw FxTrace.Exception.AsError(new ArgumentException(SR.NamespaceListArgumentMustBeNamespaceData, "value")); } int index = this.Lookup(ns.Namespace); if (index != -1) { RemoveAt(index); } } public void RemoveAt(int index) { NamespaceData ns = this.UniqueNamespaces[index]; RemoveNamespaceFromSet(ns.Namespace); this.UniqueNamespaces.RemoveAt(index); } public object this[int index] { get { return this.UniqueNamespaces[index]; } set { NamespaceData ns = value as NamespaceData; if (ns == null) { throw FxTrace.Exception.AsError(new ArgumentException(SR.NamespaceListArgumentMustBeNamespaceData, "value")); } if (Lookup(ns.Namespace) == -1) { this.SetValueAt(index, ns); this.UniqueNamespaces[index] = ns; } else { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.NamespaceListNoDuplicate)); } } } public void CopyTo(Array array, int index) { ((IList)this.UniqueNamespaces).CopyTo(array, index); } public int Count { get { return this.UniqueNamespaces.Count; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public IEnumerator GetEnumerator() { return this.UniqueNamespaces.GetEnumerator(); } public void UpdateAssemblyInfo(string importedNamespace) { this.UpdateAssemblyInfoCore(importedNamespace); } protected abstract void AddCore(NamespaceData ns); protected abstract void ClearCore(); protected abstract void InsertCore(int index, NamespaceData ns); protected abstract void RemoveNamespaceFromSet(string ns); protected abstract void SetValueAt(int index, NamespaceData ns); protected abstract void UpdateAssemblyInfoCore(string importedNamespace); } class VisualBasicNamespaceList : NamespaceList { //Since XAML generated by designer will almost always have some designer type in it, designer namespaces will appear in XAML. //And because Runtime design could not destinguish namespaces coming from XAML serialization between namespaces added by users, //designer namespaces will show up in import designer. This is bad user experience because most WF project won't reference designer //assembly. We could safely assume that customers won't use designer namespaces and type in their WF expressions, so we simply //---- designer namespaces out of the namespace list static readonly string[] BlackListedAssemblies = new string[] { typeof(ViewStateService).Assembly.GetName().FullName, typeof(ViewStateService).Assembly.GetName().Name, }; static readonly Collection<string> FrameworkAssemblies = new Collection<string> { typeof(Activity).Assembly.GetName().FullName, typeof(Activity).Assembly.GetName().Name, }; static readonly Collection<string> BlackListsedNamespaces = new Collection<string> { "System.Activities.Composition", "System.Activities.Debugger.Symbol" }; public VisualBasicNamespaceList(ISet<VisualBasicImportReference> importReferences) { this.VisualBasicImports = importReferences; foreach (string blackListedAssembly in BlackListedAssemblies) { RemoveAssemblyFromSet(blackListedAssembly); } foreach (VisualBasicImportReference import in importReferences) { if (!(BlackListsedNamespaces.Contains(import.Import) && FrameworkAssemblies.Contains(import.Assembly))) { if (Lookup(import.Import) == -1) { this.UniqueNamespaces.Add(new NamespaceData { Namespace = import.Import }); } } } } internal ISet<VisualBasicImportReference> VisualBasicImports { get; private set; } IEnumerable<VisualBasicImportReference> GetVisualBasicImportReferences(string importNamespace) { List<VisualBasicImportReference> imports = new List<VisualBasicImportReference>(); List<string> assemblies; //in rehost cases or when some assembiles are not referenced, we may not find that namespace if (!this.AvailableNamespaces.TryGetValue(importNamespace, out assemblies)) { return imports; } foreach (string assembly in assemblies) { imports.Add(new VisualBasicImportReference { Import = importNamespace, Assembly = assembly }); } return imports; } protected override void UpdateAssemblyInfoCore(string importedNamespace) { if (this.VisualBasicImports != null) { if (this.Lookup(importedNamespace) != -1) { this.VisualBasicImports.UnionWith(GetVisualBasicImportReferences(importedNamespace)); } else { Fx.Assert("UpdateAssemblyInfor should only be called for existed namespace"); } } } protected override void RemoveNamespaceFromSet(string ns) { List<VisualBasicImportReference> toRemoves = new List<VisualBasicImportReference>(); foreach (VisualBasicImportReference import in this.VisualBasicImports) { if (import.Import == ns) { toRemoves.Add(import); } } foreach (VisualBasicImportReference toRemove in toRemoves) { this.VisualBasicImports.Remove(toRemove); } } private void RemoveAssemblyFromSet(string assembly) { List<VisualBasicImportReference> toRemoves = new List<VisualBasicImportReference>(); foreach (VisualBasicImportReference import in this.VisualBasicImports) { if (import.Assembly == assembly) { toRemoves.Add(import); } } foreach (VisualBasicImportReference toRemove in toRemoves) { this.VisualBasicImports.Remove(toRemove); } } protected override void AddCore(NamespaceData ns) { this.VisualBasicImports.UnionWith(GetVisualBasicImportReferences(ns.Namespace)); } protected override void ClearCore() { this.VisualBasicImports.Clear(); } protected override void InsertCore(int index, NamespaceData ns) { this.VisualBasicImports.UnionWith(GetVisualBasicImportReferences(ns.Namespace)); } protected override void SetValueAt(int index, NamespaceData ns) { RemoveNamespaceFromSet(this.UniqueNamespaces[index].Namespace); this.VisualBasicImports.UnionWith(GetVisualBasicImportReferences(ns.Namespace)); } } class TextExpressionNamespaceList : NamespaceList { public TextExpressionNamespaceList(IList<string> importedNamespaces, IList<AssemblyReference> references) { this.TextExpressionNamespaces = importedNamespaces; this.TextExpressionReferences = references; foreach (string importedNamespace in importedNamespaces) { if (Lookup(importedNamespace) == -1) { this.UniqueNamespaces.Add(new NamespaceData { Namespace = importedNamespace }); } } } internal IList<string> TextExpressionNamespaces { get; private set; } internal IList<AssemblyReference> TextExpressionReferences { get; private set; } protected override void RemoveNamespaceFromSet(string ns) { this.TextExpressionNamespaces.Remove(ns); } internal void RemoveAssemblyFromSet(string assembly) { AssemblyReference toRemove = null; foreach (AssemblyReference reference in this.TextExpressionReferences) { if (reference.AssemblyName.Name == assembly) { toRemove = reference; break; } } if (toRemove != null) { this.TextExpressionReferences.Remove(toRemove); } } private void AddAssemblyToSet(string assembly) { bool isExisted = false; foreach (AssemblyReference reference in this.TextExpressionReferences) { if (reference.AssemblyName.Name == assembly) { isExisted = true; } } if (!isExisted) { this.TextExpressionReferences.Add(new AssemblyReference { AssemblyName = new AssemblyName(assembly) }); } } protected override void AddCore(NamespaceData ns) { this.InsertCore(this.TextExpressionNamespaces.Count, ns); } protected override void ClearCore() { this.TextExpressionNamespaces.Clear(); } protected override void InsertCore(int index, NamespaceData ns) { this.TextExpressionNamespaces.Insert(index, ns.Namespace); if (this.AvailableNamespaces.ContainsKey(ns.Namespace)) { foreach (string assembly in this.AvailableNamespaces[ns.Namespace]) { this.AddAssemblyToSet(assembly); } } } protected override void SetValueAt(int index, NamespaceData ns) { this.TextExpressionNamespaces[index] = ns.Namespace; } protected override void UpdateAssemblyInfoCore(string importedNamespace) { foreach (string assembly in this.AvailableNamespaces[importedNamespace]) { this.AddAssemblyToSet(assembly); } } } }
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using TWCore.Diagnostics.Status; using TWCore.Settings; // ReSharper disable InconsistentNaming // ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable MemberCanBePrivate.Global namespace TWCore.Diagnostics.Log.Storages { /// <inheritdoc cref="ILogStorage" /> /// <summary> /// Sends the Logs items via email using SMTP /// </summary> [SettingsContainer("MailLogStorage")] [StatusName("Mail Log")] public class MailLogStorage: SettingsBase, ILogStorage { private readonly List<ILogItem> _buffer = new List<ILogItem>(); private static bool _waiting; private static SmtpClient _smtp; #region Settings /// <summary> /// SMTP Host /// </summary> public string Host { get; set; } /// <summary> /// SMTP Port /// </summary> public int Port { get; set; } /// <summary> /// Use default SMTP Credentials /// </summary> public bool UseDefaultCredentials { get; set; } /// <summary> /// SMTP Credentials : User /// </summary> public string User { get; set; } /// <summary> /// SMTP Credentials : Password /// </summary> public string Password { get; set; } /// <summary> /// Use SSL /// </summary> public bool UseSSL { get; set; } /// <summary> /// SMTP Timeout /// </summary> public int Timeout { get; set; } /// <summary> /// SMTP Timeout /// </summary> public int BufferTimeoutInSeconds { get; set; } = 60; /// <summary> /// Log Level to send to tracked chats /// </summary> public LogLevel LevelAllowed { get; set; } = LogLevel.Error; /// <summary> /// AddressFromDisplay /// </summary> public string AddressFromDisplay { get; set; } /// <summary> /// AddressFrom /// </summary> public string AddressFrom { get; set; } /// <summary> /// AddressBcc /// </summary> public string AddressBcc { get; set; } /// <summary> /// AddressCc /// </summary> public string AddressCc { get; set; } /// <summary> /// AddressTo /// </summary> public string AddressTo { get; set; } #endregion #region .ctor /// <inheritdoc /> /// <summary> /// Sends the Logs items via email using SMTP /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public MailLogStorage() { try { SetSMTP(Host, Port, UseDefaultCredentials, User, Password, UseSSL, Timeout); } catch(Exception) { _smtp = null; } } #endregion #region Public Methods /// <summary> /// Allow change the smtp config /// </summary> /// <param name="host">Smtp server Host</param> /// <param name="port">Smtp server Port</param> /// <param name="useDefaultCredentials">Smtp server use default creadentials</param> /// <param name="user">Smtp server Username</param> /// <param name="password">Smtp server Password</param> /// <param name="useSSL">Smtp server use SSL</param> /// <param name="timeout">Smtp server Timeout</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void SetSMTP(string host, int port, bool useDefaultCredentials, string user = null, string password = null, bool useSSL = false, int timeout = 30) { if (!_waiting) { _smtp = new SmtpClient { DeliveryFormat = SmtpDeliveryFormat.International, DeliveryMethod = SmtpDeliveryMethod.Network, Host = host?.Trim(), Port = port, UseDefaultCredentials = useDefaultCredentials }; if (!useDefaultCredentials) _smtp.Credentials = new NetworkCredential(user?.Trim(), password?.Trim()); _smtp.EnableSsl = useSSL; _smtp.Timeout = (int)TimeSpan.FromSeconds(timeout).TotalMilliseconds; Core.Log.InfoDetail("SMTP changed sucessfully"); } else Core.Log.InfoBasic("Couldn't change the SMTP value because its in use"); } /// <summary> /// Allow change the smtp config /// </summary> /// <param name="smtp"></param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void SetSMTP(SmtpClient smtp) { if (!_waiting) { _smtp = smtp; Core.Log.InfoDetail("SMTP changed sucessfully"); } else Core.Log.InfoBasic("Couldn't change the SMTP value because its in use"); } /// <inheritdoc /> /// <summary> /// Writes a log item empty line /// </summary> public Task WriteEmptyLineAsync() { return Task.CompletedTask; } /// <inheritdoc /> /// <summary> /// Writes a log item to the storage /// </summary> /// <param name="item">Log Item</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Task WriteAsync(ILogItem item) { if ((LevelAllowed & item.Level) == 0 || item.Message.Contains("SMTPERROR")) return Task.CompletedTask; lock (_buffer) { _buffer.Add(new LogItem { ApplicationName = item.ApplicationName, AssemblyName = item.AssemblyName, Code = item.Code, EnvironmentName = item.EnvironmentName, Exception = item.Exception, GroupName = item.GroupName, Id = item.Id, InstanceId = item.InstanceId, Level = item.Level, MachineName = item.MachineName, Message = item.Message, ProcessName = item.ProcessName, Timestamp = item.Timestamp, TypeName = item.TypeName }); } if (_waiting) return Task.CompletedTask; _waiting = true; Task.Delay(BufferTimeoutInSeconds * 1000).ContinueWith(t => { SendEmail(); }); return Task.CompletedTask; } /// <summary> /// Writes a group metadata item to the storage /// </summary> /// <param name="item">Group metadata item</param> /// <returns>Task process</returns> public Task WriteAsync(IGroupMetadata item) { return Task.CompletedTask; } /// <inheritdoc /> /// <summary> /// Dispose the current object resources /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { SendEmail(); _buffer.Clear(); _smtp.Dispose(); } #endregion #region Private Methods [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SendEmail() { var message = new MailMessage { BodyEncoding = Encoding.UTF8, SubjectEncoding = Encoding.UTF8 }; var addFDisplay = AddressFromDisplay?.Trim(); message.From = string.IsNullOrEmpty(addFDisplay) ? new MailAddress(AddressFrom?.Trim()) : new MailAddress(AddressFrom?.Trim(), addFDisplay); AddressBcc = AddressBcc?.Replace(",", ";").Replace("|", ";"); AddressCc = AddressCc?.Replace(",", ";").Replace("|", ";"); AddressTo = AddressTo?.Replace(",", ";").Replace("|", ";"); foreach (var a in AddressBcc.SplitAndTrim(';')) { if (!string.IsNullOrEmpty(a)) message.Bcc.Add(new MailAddress(a)); } foreach (var a in AddressCc.SplitAndTrim(';')) { if (!string.IsNullOrEmpty(a)) message.CC.Add(new MailAddress(a)); } foreach (var a in AddressTo.SplitAndTrim(';')) { if (!string.IsNullOrEmpty(a)) message.To.Add(new MailAddress(a)); } var msg = string.Empty; lock (_buffer) { var first = _buffer.First(); message.Subject = _buffer.Count == 1 ? string.Format("{0} {1} {2}: {3}", first.Timestamp.ToString("dd/MM/yyyy HH:mm:ss"), first.MachineName, first.ApplicationName, first.Message) : string.Format("{0} {1} {2}: Messages", first.Timestamp.ToString("dd/MM/yyyy HH:mm:ss"), first.MachineName, first.ApplicationName); foreach (var innerItem in _buffer) { msg += string.Format("{0}\r\nMachine Name: {1} [{2}]\r\nAplicationName: {3}\r\nMessage: {4}", innerItem.Timestamp.ToString("dd/MM/yyyy HH:mm:ss"), innerItem.MachineName, innerItem.EnvironmentName, innerItem.ApplicationName, innerItem.Message); if (innerItem.Exception != null) { if (!string.IsNullOrEmpty(innerItem.Exception.ExceptionType)) msg += "\r\nException: " + innerItem.Exception.ExceptionType; if (!string.IsNullOrEmpty(innerItem.Exception.StackTrace)) msg += "\r\nStack Trace: " + innerItem.Exception.StackTrace; } if (innerItem != _buffer.Last()) msg += "\r\n-------------------------------\r\n"; } _buffer.Clear(); } message.Body = msg; if (_smtp is null) return; try { _smtp.Send(message); } catch (Exception e) { Core.Log.Error("SMTPERROR: {0}", e.Message); } finally { _waiting = false; } } #endregion } }
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) using System; using GooglePlayGames.Native.PInvoke; using System.Runtime.InteropServices; using GooglePlayGames.OurUtils; using System.Collections.Generic; using GooglePlayGames.Native.Cwrapper; using C = GooglePlayGames.Native.Cwrapper.TurnBasedMatch; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; using TBM = GooglePlayGames.BasicApi.Multiplayer.TurnBasedMatch; using GooglePlayGames.BasicApi.Multiplayer; namespace GooglePlayGames.Native.PInvoke { internal class NativeTurnBasedMatch : BaseReferenceHolder { internal NativeTurnBasedMatch(IntPtr selfPointer) : base(selfPointer) { } internal uint AvailableAutomatchSlots() { return C.TurnBasedMatch_AutomatchingSlotsAvailable(SelfPtr()); } internal ulong CreationTime() { return C.TurnBasedMatch_CreationTime(SelfPtr()); } internal IEnumerable<MultiplayerParticipant> Participants() { return PInvokeUtilities.ToEnumerable( C.TurnBasedMatch_Participants_Length(SelfPtr()), (index) => new MultiplayerParticipant( C.TurnBasedMatch_Participants_GetElement(SelfPtr(), index))); } internal uint Version() { return C.TurnBasedMatch_Version(SelfPtr()); } internal uint Variant() { return C.TurnBasedMatch_Variant(SelfPtr()); } internal ParticipantResults Results() { return new ParticipantResults(C.TurnBasedMatch_ParticipantResults(SelfPtr())); } internal MultiplayerParticipant ParticipantWithId(string participantId) { foreach (var participant in Participants()) { if (participant.Id().Equals(participantId)) { return participant; } // If this isn't the participant we're looking for, clean it up lest we leak // memory. participant.Dispose(); } return null; } internal MultiplayerParticipant PendingParticipant() { var participant = new MultiplayerParticipant( C.TurnBasedMatch_PendingParticipant(SelfPtr())); if (!participant.Valid()) { participant.Dispose(); return null; } return participant; } internal Types.MatchStatus MatchStatus() { return C.TurnBasedMatch_Status(SelfPtr()); } internal string Description() { return PInvokeUtilities.OutParamsToString( (out_string, size) => C.TurnBasedMatch_Description(SelfPtr(), out_string, size)); } internal bool HasRematchId() { return C.TurnBasedMatch_HasRematchId(SelfPtr()); } internal string RematchId() { if (!HasRematchId()) { return null; } return PInvokeUtilities.OutParamsToString( (out_string, size) => C.TurnBasedMatch_RematchId(SelfPtr(), out_string, size)); } internal byte[] Data() { if (!C.TurnBasedMatch_HasData(SelfPtr())) { Logger.d("Match has no data."); return null; } return PInvokeUtilities.OutParamsToBytes( (bytes, size) => C.TurnBasedMatch_Data(SelfPtr(), bytes, size)); } internal string Id() { return PInvokeUtilities.OutParamsToString( (out_string, size) => C.TurnBasedMatch_Id(SelfPtr(), out_string, size)); } protected override void CallDispose(HandleRef selfPointer) { C.TurnBasedMatch_Dispose(selfPointer); } internal TBM AsTurnBasedMatch(string selfPlayerId) { List<Participant> participants = new List<Participant>(); string selfParticipantId = null; string pendingParticipantId = null; using (var pending = PendingParticipant()) { if (pending != null) { pendingParticipantId = pending.Id(); } } foreach (var participant in Participants()) { using (participant) { using (var player = participant.Player()) { if (player != null && player.Id().Equals(selfPlayerId)) { selfParticipantId = participant.Id(); } } participants.Add(participant.AsParticipant()); } } // A match can be rematched if it's complete, and it hasn't already been rematched. bool canRematch = MatchStatus() == Types.MatchStatus.COMPLETED && !HasRematchId(); return new GooglePlayGames.BasicApi.Multiplayer.TurnBasedMatch( Id(), Data(), canRematch, selfParticipantId, participants, AvailableAutomatchSlots(), pendingParticipantId, ToTurnStatus(MatchStatus()), ToMatchStatus(pendingParticipantId, MatchStatus()), Variant(), Version() ); } private static TBM.MatchTurnStatus ToTurnStatus(Types.MatchStatus status) { switch (status) { case Types.MatchStatus.CANCELED: return TBM.MatchTurnStatus.Complete; case Types.MatchStatus.COMPLETED: return TBM.MatchTurnStatus.Complete; case Types.MatchStatus.EXPIRED: return TBM.MatchTurnStatus.Complete; case Types.MatchStatus.INVITED: return TBM.MatchTurnStatus.Invited; case Types.MatchStatus.MY_TURN: return TBM.MatchTurnStatus.MyTurn; case Types.MatchStatus.PENDING_COMPLETION: return TBM.MatchTurnStatus.Complete; case Types.MatchStatus.THEIR_TURN: return TBM.MatchTurnStatus.TheirTurn; default: return TBM.MatchTurnStatus.Unknown; } } private static TBM.MatchStatus ToMatchStatus( string pendingParticipantId, Types.MatchStatus status) { switch (status) { case Types.MatchStatus.CANCELED: return TBM.MatchStatus.Cancelled; case Types.MatchStatus.COMPLETED: return TBM.MatchStatus.Complete; case Types.MatchStatus.EXPIRED: return TBM.MatchStatus.Expired; case Types.MatchStatus.INVITED: return TBM.MatchStatus.Active; case Types.MatchStatus.MY_TURN: return TBM.MatchStatus.Active; case Types.MatchStatus.PENDING_COMPLETION: return TBM.MatchStatus.Complete; case Types.MatchStatus.THEIR_TURN: // If it's their turn, but we don't have a valid pending participant, it's because // we're still automatching against that participant. return pendingParticipantId == null ? TBM.MatchStatus.AutoMatching : TBM.MatchStatus.Active; default: return TBM.MatchStatus.Unknown; } } internal static NativeTurnBasedMatch FromPointer(IntPtr selfPointer) { if (PInvokeUtilities.IsNull(selfPointer)) { return null; } return new NativeTurnBasedMatch(selfPointer); } } } #endif
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Cache.Query { using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Query; /// <summary> /// SQL fields query. /// </summary> public class SqlFieldsQuery : IQueryBaseInternal { /// <summary> Default page size. </summary> public const int DefaultPageSize = 1024; /// <summary> Default value for <see cref="UpdateBatchSize"/>. </summary> public const int DefaultUpdateBatchSize = 1; /// <summary> /// Constructor. /// </summary> /// <param name="sql">SQL.</param> /// <param name="args">Arguments.</param> public SqlFieldsQuery(string sql, params object[] args) : this(sql, false, args) { // No-op. } /// <summary> /// Constructor, /// </summary> /// <param name="sql">SQL.</param> /// <param name="loc">Whether query should be executed locally.</param> /// <param name="args">Arguments.</param> public SqlFieldsQuery(string sql, bool loc, params object[] args) { Sql = sql; Local = loc; Arguments = args; PageSize = DefaultPageSize; UpdateBatchSize = DefaultUpdateBatchSize; } /// <summary> /// SQL. /// </summary> public string Sql { get; set; } /// <summary> /// Arguments. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] Arguments { get; set; } /// <summary> /// Local flag. When set query will be executed only on local node, so only local /// entries will be returned as query result. /// <para /> /// Defaults to <c>false</c>. /// </summary> public bool Local { get; set; } /// <summary> /// Optional page size. /// <para /> /// Defaults to <see cref="DefaultPageSize"/>. /// </summary> public int PageSize { get; set; } /// <summary> /// Gets or sets a value indicating whether distributed joins should be enabled for this query. /// <para /> /// When disabled, join results will only contain colocated data (joins work locally). /// When enabled, joins work as expected, no matter how the data is distributed. /// </summary> /// <value> /// <c>true</c> if enable distributed joins should be enabled; otherwise, <c>false</c>. /// </value> public bool EnableDistributedJoins { get; set; } /// <summary> /// Gets or sets a value indicating whether join order of tables should be enforced. /// <para /> /// When true, query optimizer will not reorder tables in join. /// <para /> /// It is not recommended to enable this property until you are sure that your indexes /// and the query itself are correct and tuned as much as possible but /// query optimizer still produces wrong join order. /// </summary> /// <value> /// <c>true</c> if join order should be enforced; otherwise, <c>false</c>. /// </value> public bool EnforceJoinOrder { get; set; } /// <summary> /// Gets or sets the query timeout. Query will be automatically cancelled if the execution timeout is exceeded. /// Default is <see cref="TimeSpan.Zero"/>, which means no timeout. /// </summary> public TimeSpan Timeout { get; set; } /// <summary> /// Gets or sets a value indicating whether this query contains only replicated tables. /// This is a hint for potentially more effective execution. /// </summary> [Obsolete("No longer used as of Apache Ignite 2.8.")] public bool ReplicatedOnly { get; set; } /// <summary> /// Gets or sets a value indicating whether this query operates on colocated data. /// <para /> /// Whenever Ignite executes a distributed query, it sends sub-queries to individual cluster members. /// If you know in advance that the elements of your query selection are colocated together on the same /// node and you group by colocated key (primary or affinity key), then Ignite can make significant /// performance and network optimizations by grouping data on remote nodes. /// </summary> public bool Colocated { get; set; } /// <summary> /// Gets or sets the default schema name for the query. /// <para /> /// If not set, current cache name is used, /// which means you can omit schema name for tables within the current cache. /// </summary> public string Schema { get; set; } /// <summary> /// Gets or sets a value indicating whether this <see cref="SqlFieldsQuery"/> is lazy. /// <para /> /// By default Ignite attempts to fetch the whole query result set to memory and send it to the client. /// For small and medium result sets this provides optimal performance and minimize duration of internal /// database locks, thus increasing concurrency. /// <para /> /// If result set is too big to fit in available memory this could lead to excessive GC pauses and even /// OutOfMemoryError. Use this flag as a hint for Ignite to fetch result set lazily, thus minimizing memory /// consumption at the cost of moderate performance hit. /// </summary> public bool Lazy { get; set; } /// <summary> /// Gets or sets partitions for the query. /// <para /> /// The query will be executed only on nodes which are primary for specified partitions. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] Partitions { get; set; } /// <summary> /// Gets or sets batch size for update queries. /// <para /> /// Default is 1 (<see cref="DefaultUpdateBatchSize"/>. /// </summary> public int UpdateBatchSize { get; set; } /// <summary> /// Returns a <see cref="string" /> that represents this instance. /// </summary> /// <returns> /// A <see cref="string" /> that represents this instance. /// </returns> public override string ToString() { var args = Arguments == null ? "" : string.Join(", ", Arguments.Select(x => x == null ? "null" : x.ToString())); var parts = Partitions == null ? "" : string.Join(", ", Partitions.Select(x => x.ToString())); return string.Format("SqlFieldsQuery [Sql={0}, Arguments=[{1}], Local={2}, PageSize={3}, " + "EnableDistributedJoins={4}, EnforceJoinOrder={5}, Timeout={6}, Partitions=[{7}], " + "UpdateBatchSize={8}, Colocated={9}, Schema={10}, Lazy={11}]", Sql, args, Local, PageSize, EnableDistributedJoins, EnforceJoinOrder, Timeout, parts, UpdateBatchSize, Colocated, Schema, Lazy); } /** <inheritdoc /> */ void IQueryBaseInternal.Write(BinaryWriter writer, bool keepBinary) { Write(writer); } /// <summary> /// Writes this query. /// </summary> internal void Write(BinaryWriter writer) { writer.WriteBoolean(Local); writer.WriteString(Sql); writer.WriteInt(PageSize); QueryBase.WriteQueryArgs(writer, Arguments); writer.WriteBoolean(EnableDistributedJoins); writer.WriteBoolean(EnforceJoinOrder); writer.WriteBoolean(Lazy); // Lazy flag. writer.WriteInt((int) Timeout.TotalMilliseconds); #pragma warning disable 618 writer.WriteBoolean(ReplicatedOnly); #pragma warning restore 618 writer.WriteBoolean(Colocated); writer.WriteString(Schema); // Schema writer.WriteIntArray(Partitions); writer.WriteInt(UpdateBatchSize); } /** <inheritdoc /> */ CacheOp IQueryBaseInternal.OpId { get { return CacheOp.QrySqlFields; } } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Data.SqlClient; using System.Collections; using System.Collections.Generic; using DSL.POS.DataAccessLayer.Common.Imp; using DSL.POS.DataAccessLayer.Interface; using DSL.POS.DTO.DTO; namespace DSL.POS.DataAccessLayer.Imp { /// <summary> /// Summary description for ProductBrandDALImp /// </summary> /// // Error Handling developed by Samad // 05/12/06 public class ProductBrandDALImp : CommonDALImp, IProductBrandDAL { private string Get_NewProductBrandCode(ProductBrandInfoDTO dto) { string pbCode = null; int pbCodeNo = 0; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); objCmd.CommandText = "Select Isnull(Max(cast(PB_Code as int)),0 )+1 From ProductBrandInfo"; try { objMyCon.Open(); objCmd.Connection = objMyCon; pbCodeNo = (int)objCmd.ExecuteScalar(); } catch (Exception Exp) { throw Exp; } finally { objMyCon.Close(); } pbCode = pbCodeNo.ToString("0000"); return pbCode; } public override void Save(object Obj) { ProductBrandInfoDTO dto = (ProductBrandInfoDTO)Obj; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); if (dto.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { dto.PB_Code = Get_NewProductBrandCode(dto); objCmd.CommandText = "Insert Into ProductBrandInfo(PB_Code,PB_Name,EntryBy,EntryDate) Values(@PB_Code,@PB_Name,@EntryBy,@EntryDate)"; objCmd.Parameters.Add(new SqlParameter("@PB_Code", SqlDbType.VarChar, 4)); objCmd.Parameters.Add(new SqlParameter("@PB_Name", SqlDbType.VarChar, 50)); objCmd.Parameters.Add(new SqlParameter("@EntryBy", SqlDbType.VarChar, 6)); objCmd.Parameters.Add(new SqlParameter("@EntryDate", SqlDbType.DateTime, 8)); objCmd.Parameters["@PB_Code"].Value = (string)dto.PB_Code; objCmd.Parameters["@PB_Name"].Value = (string)dto.PB_Name; objCmd.Parameters["@Entryby"].Value = (string)dto.EntryBy; objCmd.Parameters["@EntryDate"].Value = (DateTime)dto.EntryDate; } else { objCmd.CommandText = "Update ProductBrandInfo Set PB_Name=@PB_Name Where PB_PK=@PB_PK"; objCmd.Parameters.Add(new SqlParameter("@PB_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters.Add(new SqlParameter("@PB_Name", SqlDbType.VarChar, 50)); objCmd.Parameters["@PB_PK"].Value = (Guid)dto.PrimaryKey; objCmd.Parameters["@PB_Name"].Value = (string)dto.PB_Name; } try { objCmd.Connection = objMyCon; objMyCon.Open(); objCmd.ExecuteNonQuery(); } catch (Exception Exp) { throw Exp; } finally { objMyCon.Close(); } } public override void Delete(object PrimaryKey) { ProductBrandInfoDTO dto = (ProductBrandInfoDTO)PrimaryKey; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); objCmd.CommandText = "Delete From ProductBrandInfo Where PB_PK=@PB_PK"; objCmd.Parameters.Add(new SqlParameter("@PB_PK", SqlDbType.UniqueIdentifier, 16)); objCmd.Parameters["@PB_PK"].Value = (Guid)dto.PrimaryKey; objCmd.Connection = objMyCon; try { objMyCon.Open(); objCmd.ExecuteNonQuery(); } catch (Exception Exp) { throw Exp; } finally { objMyCon.Close(); } } public List<ProductBrandInfoDTO> GetProductBrand() { List<ProductBrandInfoDTO> productBrandiList = new List<ProductBrandInfoDTO>(); SqlDataReader DR; SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = new SqlCommand(); objCmd.Connection = objMyCon; objCmd.CommandText = "SELECT PB_PK, PB_Code, PB_Name FROM ProductBrandInfo ORDER BY PB_Code DESC"; try { objMyCon.Open(); DR = objCmd.ExecuteReader(); } catch (Exception Exp) { throw Exp; } while (DR.Read()) { ProductBrandInfoDTO pbDto = new ProductBrandInfoDTO();//(Guid)DR[0],(string)DR[1],(string)DR[1]); pbDto.PrimaryKey = (Guid)DR[0]; pbDto.PB_Code = (string)DR[1]; pbDto.PB_Name = (string)DR[2]; productBrandiList.Add(pbDto); } DR.Close(); objMyCon.Close(); return productBrandiList; } public ArrayList GetData() { SqlConnection objMyCon = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCom = new SqlCommand(); ArrayList brandList = new ArrayList(); SqlDataReader reader; objCom.Connection = objMyCon; objCom.CommandText = "SELECT PB_PK, PB_Code, PB_Name FROM ProductBrandInfo ORDER BY PB_Code DESC"; try { objMyCon.Open(); reader = objCom.ExecuteReader(); } catch (Exception Exp) { throw Exp; } while (reader.Read()) { ProductBrandInfoDTO dto = Populate(reader); brandList.Add(dto); } reader.Close(); reader.Dispose(); return brandList; } public ProductBrandInfoDTO FindByPK(Guid pk) { ProductBrandInfoDTO pbDTO = new ProductBrandInfoDTO(); string sqlSelect = "SELECT PB_PK, PB_Code, PB_Name FROM ProductBrandInfo WHERE PB_PK=@PB_PK"; SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DPOSConnectionString"].ToString()); SqlCommand objCmd = sqlConn.CreateCommand(); try { objCmd.CommandText = sqlSelect; objCmd.Connection = sqlConn; objCmd.Parameters.Add("@PB_PK", SqlDbType.UniqueIdentifier, 16); objCmd.Parameters["@PB_PK"].Value = pk; sqlConn.Open(); SqlDataReader thisReader = objCmd.ExecuteReader(); while (thisReader.Read()) { pbDTO = Populate(thisReader); } thisReader.Close(); thisReader.Dispose(); } catch (Exception Exp) { throw Exp; } finally { objCmd.Dispose(); objCmd.Cancel(); sqlConn.Dispose(); sqlConn.Close(); } return pbDTO; } public ProductBrandInfoDTO Populate(SqlDataReader reader) { try { ProductBrandInfoDTO dto = new ProductBrandInfoDTO(); dto.PrimaryKey = (Guid)reader["PB_PK"]; dto.PB_Code = (string)reader["PB_Code"]; dto.PB_Name = (string)reader["PB_Name"]; return dto; } catch (Exception Exp) { throw Exp; } } public ProductBrandDALImp() { // // TODO: Add constructor logic here // } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.LiveTests; using Google.GData.Extensions; using Google.GData.Calendar; namespace Google.GData.Client.UnitTests { [TestFixture] public class BaseTestClass { /// <summary>default extension for temp files. They do get removed after a successful run</summary> protected static string defExt = ".log"; /// <summary>holds the default localhost address</summary> protected string defaultHost; /// <summary>holds the default external host</summary> protected string strRemoteHost; /// <summary>holds the default remote host address</summary> protected IDictionary externalHosts; /// <summary>holds the number of iterations for the tests</summary> protected int iIterations; /// <summary>holds the logging factory</summary> protected IGDataRequestFactory factory; /// <summary>holds the configuration of the test found in the dll.config file</summary> protected IDictionary unitTestConfiguration; /// <summary>holds path to resources (xml files, jpgs) that are used during the unittests</summary> protected string resourcePath = ""; /// <summary>default empty constructor</summary> public BaseTestClass() { } public virtual string ServiceName { get { return "cl"; } } public virtual string ApplicationName { get { return "UnitTests"; } } /// <summary>the setup method</summary> [SetUp] public virtual void InitTest() { Tracing.InitTracing(); this.defaultHost = "http://localhost"; this.strRemoteHost = null; this.externalHosts = null; this.iIterations = 10; if (this.factory == null) { GDataLoggingRequestFactory factory = new GDataLoggingRequestFactory(this.ServiceName, this.ApplicationName); this.factory = (IGDataRequestFactory)factory; } ReadConfigFile(); } /// <summary>private void ReadConfigFile()</summary> /// <returns> </returns> protected virtual void ReadConfigFile() { this.unitTestConfiguration = (IDictionary)ConfigurationManager.GetSection("unitTestSection"); // no need to go further if the configuration file is needed. if (unitTestConfiguration == null) throw new FileNotFoundException("The DLL configuration file wasn't found, aborting."); if (unitTestConfiguration.Contains("defHost")) { this.defaultHost = (string)unitTestConfiguration["defHost"]; Tracing.TraceInfo("Read defaultHost value: " + this.defaultHost); } if (unitTestConfiguration.Contains("defRemoteHost")) { this.strRemoteHost = (string)unitTestConfiguration["defRemoteHost"]; Tracing.TraceInfo("Read default remote host value: " + this.strRemoteHost); } if (unitTestConfiguration.Contains("iteration")) { this.iIterations = int.Parse((string)unitTestConfiguration["iteration"]); } if (unitTestConfiguration.Contains("resourcePath")) { this.resourcePath = (string)unitTestConfiguration["resourcePath"]; } if (unitTestConfiguration.Contains("requestlogging")) { bool flag = bool.Parse((string)unitTestConfiguration["requestlogging"]); if (!flag) { // we are creating the logging factory by default. If // tester set's it off, create the standard factory. this.factory = new GDataGAuthRequestFactory(this.ServiceName, this.ApplicationName); } } this.externalHosts = (IDictionary)ConfigurationManager.GetSection("unitTestExternalHosts"); } /// <summary>the end it all method</summary> [TearDown] public virtual void EndTest() { Tracing.ExitTracing(); } /// <summary>private string CreateDumpFileName(string baseName)</summary> /// <param name="baseName">the basename</param> /// <returns>the complete filename for file creation</returns> protected string CreateDumpFileName(string baseName) { return Path.GetTempPath() + Path.DirectorySeparatorChar + baseName + BaseTestClass.defExt; } /// <summary>private string CreateUriFileName(string baseName)</summary> /// <param name="baseName">the basename</param> /// <returns>the complete Uri name for file access</returns> protected string CreateUriLogFileName(string baseName) { return CreateUriFileName(baseName + BaseTestClass.defExt); } /// <summary>private string CreateUriFileName(string baseName)</summary> /// <param name="baseName">the basename</param> /// <returns>the complete Uri name for file access</returns> protected string CreateUriFileName(string fileName) { string fileAndPath = Path.GetTempPath() + "/" + fileName; return CreateUri(fileAndPath); } /// <summary>private string CreateUriFileName(string baseName)</summary> /// <param name="baseName">the basename</param> /// <returns>the complete Uri name for file access</returns> protected string CreateUri(string fileAndPathName) { string strUri = null; try { UriBuilder temp = new UriBuilder("file", "localhost", 0, fileAndPathName); strUri = temp.Uri.AbsoluteUri; } catch (System.UriFormatException) { UriBuilder temp = new UriBuilder("file", "", 0, fileAndPathName); strUri = temp.Uri.AbsoluteUri; } return (strUri); } /// <summary> /// eventhandling. called when a new entry is parsed /// </summary> /// <param name="sender"> the object which send the event</param> /// <param name="e">FeedParserEventArguments, holds the feedentry</param> /// <returns> </returns> protected void OnParsedNewEntry(object sender, FeedParserEventArgs e) { if (e == null) { throw new ArgumentNullException("e"); } if (e.CreatingEntry) { Tracing.TraceMsg("\t top level event dispatcher - new Entry"); e.Entry = new MyEntry(); } } /// <summary>eventhandler - called for new extension element</summary> /// <param name="sender"> the object which send the event</param> /// <param name="e">FeedParserEventArguments, holds the feedentry</param> /// <returns> </returns> protected void OnNewExtensionElement(object sender, ExtensionElementEventArgs e) { // by default, if our event chain is not hooked, the underlying parser will add it Tracing.TraceCall("received new extension element notification"); Tracing.Assert(e != null, "e should not be null"); if (e == null) { throw new ArgumentNullException("e"); } Tracing.TraceMsg("\t top level event = new extension"); if (String.Compare(e.ExtensionElement.NamespaceURI, "http://purl.org/dc/elements/1.1/", true) == 0) { // found DC namespace Tracing.TraceMsg("\t top level event = new DC extension"); if (e.ExtensionElement.LocalName == "date") { MyEntry entry = e.Base as MyEntry; if (entry != null) { entry.DCDate = DateTime.Parse(e.ExtensionElement.InnerText); e.DiscardEntry = true; } } } } } /// <summary> /// this is just a dummy class to test new tests. Use the Ignore on the fixutre to disable or enable one class /// </summary> [TestFixture] public class InDevTests : IBaseWalkerAction { /// <summary> /// basic public constructor for Nunit /// </summary> public InDevTests() { } /// <summary>public bool Go(AtomBase baseObject)</summary> /// <param name="baseObject">object to do something with </param> /// <returns>true if we are done walking the tree</returns> public bool Go(AtomBase baseObject) { Tracing.TraceInfo("inside go: " + baseObject.ToString() + " is dirty set: " + baseObject.IsDirty().ToString()); return false; } /// <summary> /// the setup method /// </summary> [SetUp] public virtual void InitTest() { } /// <summary> /// creates a number or rows and delets them again /// </summary> [Test] public void TestIt() { Tracing.TraceMsg("Entering TestIt"); } } /// <summary> /// a subclass that is used to represent the tree in the extension testcase /// </summary> public class MyEntry : AtomEntry { private DateTime dcDate; /// <summary> /// saves the inner state of the element /// </summary> /// <param name="writer"> /// the xmlWriter to save into /// </param> protected override void SaveInnerXml(XmlWriter writer) { base.SaveInnerXml(writer); writer.WriteElementString("date", "http://purl.org/dc/elements/1.1/", this.dcDate.ToString()); } /// <summary> /// accessor method public DateTime DCDate /// </summary> /// <returns> </returns> public DateTime DCDate { get { return this.dcDate; } set { this.dcDate = 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 gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcpv = Google.Cloud.PubSub.V1; using sys = System; namespace Google.Cloud.PubSub.V1 { /// <summary>Resource name for the <c>Topic</c> resource.</summary> public sealed partial class TopicName : gax::IResourceName, sys::IEquatable<TopicName> { /// <summary>The possible contents of <see cref="TopicName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/topics/{topic}</c>.</summary> ProjectTopic = 1, /// <summary>A resource name with pattern <c>_deleted-topic_</c>.</summary> DeletedTopic = 2, } private static gax::PathTemplate s_projectTopic = new gax::PathTemplate("projects/{project}/topics/{topic}"); private static gax::PathTemplate s_deletedTopic = new gax::PathTemplate("_deleted-topic_"); /// <summary>Creates a <see cref="TopicName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="TopicName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TopicName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TopicName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TopicName"/> with the pattern <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns> public static TopicName FromProjectTopic(string projectId, string topicId) => new TopicName(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary>Creates a <see cref="TopicName"/> with the pattern <c>_deleted-topic_</c>.</summary> /// <returns>A new instance of <see cref="TopicName"/> constructed from the provided ids.</returns> public static TopicName FromDeletedTopic() => new TopicName(ResourceNameType.DeletedTopic); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string Format(string projectId, string topicId) => FormatProjectTopic(projectId, topicId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>projects/{project}/topics/{topic}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>projects/{project}/topics/{topic}</c> /// . /// </returns> public static string FormatProjectTopic(string projectId, string topicId) => s_projectTopic.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TopicName"/> with pattern /// <c>_deleted-topic_</c>. /// </summary> /// <returns> /// The string representation of this <see cref="TopicName"/> with pattern <c>_deleted-topic_</c>. /// </returns> public static string FormatDeletedTopic() => s_deletedTopic.Expand(); /// <summary>Parses the given resource name string into a new <see cref="TopicName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/topics/{topic}</c></description></item> /// <item><description><c>_deleted-topic_</c></description></item> /// </list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName) => Parse(topicName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TopicName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/topics/{topic}</c></description></item> /// <item><description><c>_deleted-topic_</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="TopicName"/> if successful.</returns> public static TopicName Parse(string topicName, bool allowUnparsed) => TryParse(topicName, allowUnparsed, out TopicName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/topics/{topic}</c></description></item> /// <item><description><c>_deleted-topic_</c></description></item> /// </list> /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string topicName, out TopicName result) => TryParse(topicName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TopicName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/topics/{topic}</c></description></item> /// <item><description><c>_deleted-topic_</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="topicName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="TopicName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string topicName, bool allowUnparsed, out TopicName result) { gax::GaxPreconditions.CheckNotNull(topicName, nameof(topicName)); gax::TemplatedResourceName resourceName; if (s_projectTopic.TryParseName(topicName, out resourceName)) { result = FromProjectTopic(resourceName[0], resourceName[1]); return true; } if (s_deletedTopic.TryParseName(topicName, out resourceName)) { result = FromDeletedTopic(); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(topicName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TopicName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string topicId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; TopicId = topicId; } /// <summary> /// Constructs a new instance of a <see cref="TopicName"/> class from the component parts of pattern /// <c>projects/{project}/topics/{topic}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="topicId">The <c>Topic</c> ID. Must not be <c>null</c> or empty.</param> public TopicName(string projectId, string topicId) : this(ResourceNameType.ProjectTopic, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), topicId: gax::GaxPreconditions.CheckNotNullOrEmpty(topicId, nameof(topicId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Topic</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string TopicId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectTopic: return s_projectTopic.Expand(ProjectId, TopicId); case ResourceNameType.DeletedTopic: return s_deletedTopic.Expand(); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as TopicName); /// <inheritdoc/> public bool Equals(TopicName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TopicName a, TopicName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TopicName a, TopicName b) => !(a == b); } /// <summary>Resource name for the <c>Subscription</c> resource.</summary> public sealed partial class SubscriptionName : gax::IResourceName, sys::IEquatable<SubscriptionName> { /// <summary>The possible contents of <see cref="SubscriptionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/subscriptions/{subscription}</c>.</summary> ProjectSubscription = 1, } private static gax::PathTemplate s_projectSubscription = new gax::PathTemplate("projects/{project}/subscriptions/{subscription}"); /// <summary>Creates a <see cref="SubscriptionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SubscriptionName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static SubscriptionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SubscriptionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SubscriptionName"/> with the pattern <c>projects/{project}/subscriptions/{subscription}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="subscriptionId">The <c>Subscription</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SubscriptionName"/> constructed from the provided ids.</returns> public static SubscriptionName FromProjectSubscription(string projectId, string subscriptionId) => new SubscriptionName(ResourceNameType.ProjectSubscription, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), subscriptionId: gax::GaxPreconditions.CheckNotNullOrEmpty(subscriptionId, nameof(subscriptionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SubscriptionName"/> with pattern /// <c>projects/{project}/subscriptions/{subscription}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="subscriptionId">The <c>Subscription</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SubscriptionName"/> with pattern /// <c>projects/{project}/subscriptions/{subscription}</c>. /// </returns> public static string Format(string projectId, string subscriptionId) => FormatProjectSubscription(projectId, subscriptionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SubscriptionName"/> with pattern /// <c>projects/{project}/subscriptions/{subscription}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="subscriptionId">The <c>Subscription</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SubscriptionName"/> with pattern /// <c>projects/{project}/subscriptions/{subscription}</c>. /// </returns> public static string FormatProjectSubscription(string projectId, string subscriptionId) => s_projectSubscription.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(subscriptionId, nameof(subscriptionId))); /// <summary>Parses the given resource name string into a new <see cref="SubscriptionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/subscriptions/{subscription}</c></description></item> /// </list> /// </remarks> /// <param name="subscriptionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SubscriptionName"/> if successful.</returns> public static SubscriptionName Parse(string subscriptionName) => Parse(subscriptionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SubscriptionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/subscriptions/{subscription}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="subscriptionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SubscriptionName"/> if successful.</returns> public static SubscriptionName Parse(string subscriptionName, bool allowUnparsed) => TryParse(subscriptionName, allowUnparsed, out SubscriptionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SubscriptionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/subscriptions/{subscription}</c></description></item> /// </list> /// </remarks> /// <param name="subscriptionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SubscriptionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string subscriptionName, out SubscriptionName result) => TryParse(subscriptionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SubscriptionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/subscriptions/{subscription}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="subscriptionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SubscriptionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string subscriptionName, bool allowUnparsed, out SubscriptionName result) { gax::GaxPreconditions.CheckNotNull(subscriptionName, nameof(subscriptionName)); gax::TemplatedResourceName resourceName; if (s_projectSubscription.TryParseName(subscriptionName, out resourceName)) { result = FromProjectSubscription(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(subscriptionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SubscriptionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string subscriptionId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; SubscriptionId = subscriptionId; } /// <summary> /// Constructs a new instance of a <see cref="SubscriptionName"/> class from the component parts of pattern /// <c>projects/{project}/subscriptions/{subscription}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="subscriptionId">The <c>Subscription</c> ID. Must not be <c>null</c> or empty.</param> public SubscriptionName(string projectId, string subscriptionId) : this(ResourceNameType.ProjectSubscription, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), subscriptionId: gax::GaxPreconditions.CheckNotNullOrEmpty(subscriptionId, nameof(subscriptionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Subscription</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string SubscriptionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectSubscription: return s_projectSubscription.Expand(ProjectId, SubscriptionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SubscriptionName); /// <inheritdoc/> public bool Equals(SubscriptionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SubscriptionName a, SubscriptionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SubscriptionName a, SubscriptionName b) => !(a == b); } /// <summary>Resource name for the <c>Snapshot</c> resource.</summary> public sealed partial class SnapshotName : gax::IResourceName, sys::IEquatable<SnapshotName> { /// <summary>The possible contents of <see cref="SnapshotName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary>A resource name with pattern <c>projects/{project}/snapshots/{snapshot}</c>.</summary> ProjectSnapshot = 1, } private static gax::PathTemplate s_projectSnapshot = new gax::PathTemplate("projects/{project}/snapshots/{snapshot}"); /// <summary>Creates a <see cref="SnapshotName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SnapshotName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static SnapshotName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SnapshotName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SnapshotName"/> with the pattern <c>projects/{project}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SnapshotName"/> constructed from the provided ids.</returns> public static SnapshotName FromProjectSnapshot(string projectId, string snapshotId) => new SnapshotName(ResourceNameType.ProjectSnapshot, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), snapshotId: gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/snapshots/{snapshot}</c>. /// </returns> public static string Format(string projectId, string snapshotId) => FormatProjectSnapshot(projectId, snapshotId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/snapshots/{snapshot}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SnapshotName"/> with pattern /// <c>projects/{project}/snapshots/{snapshot}</c>. /// </returns> public static string FormatProjectSnapshot(string projectId, string snapshotId) => s_projectSnapshot.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))); /// <summary>Parses the given resource name string into a new <see cref="SnapshotName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/snapshots/{snapshot}</c></description></item> /// </list> /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns> public static SnapshotName Parse(string snapshotName) => Parse(snapshotName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SnapshotName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/snapshots/{snapshot}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SnapshotName"/> if successful.</returns> public static SnapshotName Parse(string snapshotName, bool allowUnparsed) => TryParse(snapshotName, allowUnparsed, out SnapshotName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SnapshotName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/snapshots/{snapshot}</c></description></item> /// </list> /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SnapshotName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string snapshotName, out SnapshotName result) => TryParse(snapshotName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SnapshotName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/snapshots/{snapshot}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="snapshotName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SnapshotName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string snapshotName, bool allowUnparsed, out SnapshotName result) { gax::GaxPreconditions.CheckNotNull(snapshotName, nameof(snapshotName)); gax::TemplatedResourceName resourceName; if (s_projectSnapshot.TryParseName(snapshotName, out resourceName)) { result = FromProjectSnapshot(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(snapshotName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SnapshotName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string projectId = null, string snapshotId = null) { Type = type; UnparsedResource = unparsedResourceName; ProjectId = projectId; SnapshotId = snapshotId; } /// <summary> /// Constructs a new instance of a <see cref="SnapshotName"/> class from the component parts of pattern /// <c>projects/{project}/snapshots/{snapshot}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="snapshotId">The <c>Snapshot</c> ID. Must not be <c>null</c> or empty.</param> public SnapshotName(string projectId, string snapshotId) : this(ResourceNameType.ProjectSnapshot, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), snapshotId: gax::GaxPreconditions.CheckNotNullOrEmpty(snapshotId, nameof(snapshotId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Snapshot</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SnapshotId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectSnapshot: return s_projectSnapshot.Expand(ProjectId, SnapshotId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SnapshotName); /// <inheritdoc/> public bool Equals(SnapshotName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SnapshotName a, SnapshotName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SnapshotName a, SnapshotName b) => !(a == b); } public partial class SchemaSettings { /// <summary><see cref="SchemaName"/>-typed view over the <see cref="Schema"/> resource name property.</summary> public SchemaName SchemaAsSchemaName { get => string.IsNullOrEmpty(Schema) ? null : SchemaName.Parse(Schema, allowUnparsed: true); set => Schema = value?.ToString() ?? ""; } } public partial class Topic { /// <summary> /// <see cref="gcpv::TopicName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::TopicName TopicName { get => string.IsNullOrEmpty(Name) ? null : gcpv::TopicName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetTopicRequest { /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class PublishRequest { /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class ListTopicsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Project"/> resource name property. /// </summary> public gagr::ProjectName ProjectAsProjectName { get => string.IsNullOrEmpty(Project) ? null : gagr::ProjectName.Parse(Project, allowUnparsed: true); set => Project = value?.ToString() ?? ""; } } public partial class ListTopicSubscriptionsRequest { /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class ListTopicSubscriptionsResponse { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscriptions"/> resource name property. /// </summary> public gax::ResourceNameList<SubscriptionName> SubscriptionsAsSubscriptionNames { get => new gax::ResourceNameList<SubscriptionName>(Subscriptions, s => string.IsNullOrEmpty(s) ? null : SubscriptionName.Parse(s, allowUnparsed: true)); } } public partial class ListTopicSnapshotsRequest { /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class DeleteTopicRequest { /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class DetachSubscriptionRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class Subscription { /// <summary> /// <see cref="gcpv::SubscriptionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SubscriptionName SubscriptionName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SubscriptionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class GetSubscriptionRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class ListSubscriptionsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Project"/> resource name property. /// </summary> public gagr::ProjectName ProjectAsProjectName { get => string.IsNullOrEmpty(Project) ? null : gagr::ProjectName.Parse(Project, allowUnparsed: true); set => Project = value?.ToString() ?? ""; } } public partial class DeleteSubscriptionRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class ModifyPushConfigRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class PullRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class ModifyAckDeadlineRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class AcknowledgeRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class StreamingPullRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class CreateSnapshotRequest { /// <summary> /// <see cref="gcpv::SnapshotName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SnapshotName SnapshotName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SnapshotName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } } public partial class Snapshot { /// <summary> /// <see cref="gcpv::SnapshotName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcpv::SnapshotName SnapshotName { get => string.IsNullOrEmpty(Name) ? null : gcpv::SnapshotName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } /// <summary><see cref="TopicName"/>-typed view over the <see cref="Topic"/> resource name property.</summary> public TopicName TopicAsTopicName { get => string.IsNullOrEmpty(Topic) ? null : TopicName.Parse(Topic, allowUnparsed: true); set => Topic = value?.ToString() ?? ""; } } public partial class GetSnapshotRequest { /// <summary> /// <see cref="SnapshotName"/>-typed view over the <see cref="Snapshot"/> resource name property. /// </summary> public SnapshotName SnapshotAsSnapshotName { get => string.IsNullOrEmpty(Snapshot) ? null : SnapshotName.Parse(Snapshot, allowUnparsed: true); set => Snapshot = value?.ToString() ?? ""; } } public partial class ListSnapshotsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Project"/> resource name property. /// </summary> public gagr::ProjectName ProjectAsProjectName { get => string.IsNullOrEmpty(Project) ? null : gagr::ProjectName.Parse(Project, allowUnparsed: true); set => Project = value?.ToString() ?? ""; } } public partial class DeleteSnapshotRequest { /// <summary> /// <see cref="SnapshotName"/>-typed view over the <see cref="Snapshot"/> resource name property. /// </summary> public SnapshotName SnapshotAsSnapshotName { get => string.IsNullOrEmpty(Snapshot) ? null : SnapshotName.Parse(Snapshot, allowUnparsed: true); set => Snapshot = value?.ToString() ?? ""; } } public partial class SeekRequest { /// <summary> /// <see cref="SubscriptionName"/>-typed view over the <see cref="Subscription"/> resource name property. /// </summary> public SubscriptionName SubscriptionAsSubscriptionName { get => string.IsNullOrEmpty(Subscription) ? null : SubscriptionName.Parse(Subscription, allowUnparsed: true); set => Subscription = value?.ToString() ?? ""; } /// <summary> /// <see cref="SnapshotName"/>-typed view over the <see cref="Snapshot"/> resource name property. /// </summary> public SnapshotName SnapshotAsSnapshotName { get => string.IsNullOrEmpty(Snapshot) ? null : SnapshotName.Parse(Snapshot, allowUnparsed: true); set => Snapshot = value?.ToString() ?? ""; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.OptionalModules.Avatar.Chat { // An instance of this class exists for each unique combination of // IRC chat interface characteristics, as determined by the supplied // configuration file. internal class ChannelState { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static Regex arg = new Regex(@"\[[^\[\]]*\]"); private static int _idk_ = 0; private static int DEBUG_CHANNEL = 2147483647; // These are the IRC Connector configurable parameters with hard-wired // default values (retained for compatability). internal string Server = null; internal string Password = null; internal string IrcChannel = null; internal string BaseNickname = "OSimBot"; internal uint Port = 6667; internal string User = null; internal bool ClientReporting = true; internal bool RelayChat = true; internal bool RelayPrivateChannels = false; internal int RelayChannel = 1; internal List<int> ValidInWorldChannels = new List<int>(); // Connector agnostic parameters. These values are NOT shared with the // connector and do not differentiate at an IRC level internal string PrivateMessageFormat = "PRIVMSG {0} :<{2}> {1} {3}"; internal string NoticeMessageFormat = "PRIVMSG {0} :<{2}> {3}"; internal int RelayChannelOut = -1; internal bool RandomizeNickname = true; internal bool CommandsEnabled = false; internal int CommandChannel = -1; internal int ConnectDelay = 10; internal int PingDelay = 15; internal string DefaultZone = "Sim"; internal string _accessPassword = String.Empty; internal Regex AccessPasswordRegex = null; internal List<string> ExcludeList = new List<string>(); internal string AccessPassword { get { return _accessPassword; } set { _accessPassword = value; AccessPasswordRegex = new Regex(String.Format(@"^{0},\s*(?<avatar>[^,]+),\s*(?<message>.+)$", _accessPassword), RegexOptions.Compiled); } } // IRC connector reference internal IRCConnector irc = null; internal int idn = _idk_++; // List of regions dependent upon this connection internal List<RegionState> clientregions = new List<RegionState>(); // Needed by OpenChannel internal ChannelState() { } // This constructor is used by the Update* methods. A copy of the // existing channel state is created, and distinguishing characteristics // are copied across. internal ChannelState(ChannelState model) { Server = model.Server; Password = model.Password; IrcChannel = model.IrcChannel; Port = model.Port; BaseNickname = model.BaseNickname; RandomizeNickname = model.RandomizeNickname; User = model.User; CommandsEnabled = model.CommandsEnabled; CommandChannel = model.CommandChannel; RelayChat = model.RelayChat; RelayPrivateChannels = model.RelayPrivateChannels; RelayChannelOut = model.RelayChannelOut; RelayChannel = model.RelayChannel; ValidInWorldChannels = model.ValidInWorldChannels; PrivateMessageFormat = model.PrivateMessageFormat; NoticeMessageFormat = model.NoticeMessageFormat; ClientReporting = model.ClientReporting; AccessPassword = model.AccessPassword; DefaultZone = model.DefaultZone; ConnectDelay = model.ConnectDelay; PingDelay = model.PingDelay; } // Read the configuration file, performing variable substitution and any // necessary aliasing. See accompanying documentation for how this works. // If you don't need variables, then this works exactly as before. // If either channel or server are not specified, the request fails. internal static void OpenChannel(RegionState rs, IConfig config) { // Create a new instance of a channel. This may not actually // get used if an equivalent channel already exists. ChannelState cs = new ChannelState(); // Read in the configuration file and filter everything for variable // subsititution. m_log.DebugFormat("[IRC-Channel-{0}] Initial request by Region {1} to connect to IRC", cs.idn, rs.Region); cs.Server = Substitute(rs, config.GetString("server", null)); m_log.DebugFormat("[IRC-Channel-{0}] Server : <{1}>", cs.idn, cs.Server); cs.Password = Substitute(rs, config.GetString("password", null)); // probably not a good idea to put a password in the log file cs.User = Substitute(rs, config.GetString("user", null)); cs.IrcChannel = Substitute(rs, config.GetString("channel", null)); m_log.DebugFormat("[IRC-Channel-{0}] IrcChannel : <{1}>", cs.idn, cs.IrcChannel); cs.Port = Convert.ToUInt32(Substitute(rs, config.GetString("port", Convert.ToString(cs.Port)))); m_log.DebugFormat("[IRC-Channel-{0}] Port : <{1}>", cs.idn, cs.Port); cs.BaseNickname = Substitute(rs, config.GetString("nick", cs.BaseNickname)); m_log.DebugFormat("[IRC-Channel-{0}] BaseNickname : <{1}>", cs.idn, cs.BaseNickname); cs.RandomizeNickname = Convert.ToBoolean(Substitute(rs, config.GetString("randomize_nick", Convert.ToString(cs.RandomizeNickname)))); m_log.DebugFormat("[IRC-Channel-{0}] RandomizeNickname : <{1}>", cs.idn, cs.RandomizeNickname); cs.RandomizeNickname = Convert.ToBoolean(Substitute(rs, config.GetString("nicknum", Convert.ToString(cs.RandomizeNickname)))); m_log.DebugFormat("[IRC-Channel-{0}] RandomizeNickname : <{1}>", cs.idn, cs.RandomizeNickname); cs.User = Substitute(rs, config.GetString("username", cs.User)); m_log.DebugFormat("[IRC-Channel-{0}] User : <{1}>", cs.idn, cs.User); cs.CommandsEnabled = Convert.ToBoolean(Substitute(rs, config.GetString("commands_enabled", Convert.ToString(cs.CommandsEnabled)))); m_log.DebugFormat("[IRC-Channel-{0}] CommandsEnabled : <{1}>", cs.idn, cs.CommandsEnabled); cs.CommandChannel = Convert.ToInt32(Substitute(rs, config.GetString("commandchannel", Convert.ToString(cs.CommandChannel)))); m_log.DebugFormat("[IRC-Channel-{0}] CommandChannel : <{1}>", cs.idn, cs.CommandChannel); cs.CommandChannel = Convert.ToInt32(Substitute(rs, config.GetString("command_channel", Convert.ToString(cs.CommandChannel)))); m_log.DebugFormat("[IRC-Channel-{0}] CommandChannel : <{1}>", cs.idn, cs.CommandChannel); cs.RelayChat = Convert.ToBoolean(Substitute(rs, config.GetString("relay_chat", Convert.ToString(cs.RelayChat)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayChat : <{1}>", cs.idn, cs.RelayChat); cs.RelayPrivateChannels = Convert.ToBoolean(Substitute(rs, config.GetString("relay_private_channels", Convert.ToString(cs.RelayPrivateChannels)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayPrivateChannels : <{1}>", cs.idn, cs.RelayPrivateChannels); cs.RelayPrivateChannels = Convert.ToBoolean(Substitute(rs, config.GetString("useworldcomm", Convert.ToString(cs.RelayPrivateChannels)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayPrivateChannels : <{1}>", cs.idn, cs.RelayPrivateChannels); cs.RelayChannelOut = Convert.ToInt32(Substitute(rs, config.GetString("relay_private_channel_out", Convert.ToString(cs.RelayChannelOut)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayChannelOut : <{1}>", cs.idn, cs.RelayChannelOut); cs.RelayChannel = Convert.ToInt32(Substitute(rs, config.GetString("relay_private_channel_in", Convert.ToString(cs.RelayChannel)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayChannel : <{1}>", cs.idn, cs.RelayChannel); cs.RelayChannel = Convert.ToInt32(Substitute(rs, config.GetString("inchannel", Convert.ToString(cs.RelayChannel)))); m_log.DebugFormat("[IRC-Channel-{0}] RelayChannel : <{1}>", cs.idn, cs.RelayChannel); cs.PrivateMessageFormat = Substitute(rs, config.GetString("msgformat", cs.PrivateMessageFormat)); m_log.DebugFormat("[IRC-Channel-{0}] PrivateMessageFormat : <{1}>", cs.idn, cs.PrivateMessageFormat); cs.NoticeMessageFormat = Substitute(rs, config.GetString("noticeformat", cs.NoticeMessageFormat)); m_log.DebugFormat("[IRC-Channel-{0}] NoticeMessageFormat : <{1}>", cs.idn, cs.NoticeMessageFormat); cs.ClientReporting = Convert.ToInt32(Substitute(rs, config.GetString("verbosity", cs.ClientReporting ? "1" : "0"))) > 0; m_log.DebugFormat("[IRC-Channel-{0}] ClientReporting : <{1}>", cs.idn, cs.ClientReporting); cs.ClientReporting = Convert.ToBoolean(Substitute(rs, config.GetString("report_clients", Convert.ToString(cs.ClientReporting)))); m_log.DebugFormat("[IRC-Channel-{0}] ClientReporting : <{1}>", cs.idn, cs.ClientReporting); cs.DefaultZone = Substitute(rs, config.GetString("fallback_region", cs.DefaultZone)); m_log.DebugFormat("[IRC-Channel-{0}] DefaultZone : <{1}>", cs.idn, cs.DefaultZone); cs.ConnectDelay = Convert.ToInt32(Substitute(rs, config.GetString("connect_delay", Convert.ToString(cs.ConnectDelay)))); m_log.DebugFormat("[IRC-Channel-{0}] ConnectDelay : <{1}>", cs.idn, cs.ConnectDelay); cs.PingDelay = Convert.ToInt32(Substitute(rs, config.GetString("ping_delay", Convert.ToString(cs.PingDelay)))); m_log.DebugFormat("[IRC-Channel-{0}] PingDelay : <{1}>", cs.idn, cs.PingDelay); cs.AccessPassword = Substitute(rs, config.GetString("access_password", cs.AccessPassword)); m_log.DebugFormat("[IRC-Channel-{0}] AccessPassword : <{1}>", cs.idn, cs.AccessPassword); string[] excludes = config.GetString("exclude_list", "").Trim().Split(new Char[] { ',' }); cs.ExcludeList = new List<string>(excludes.Length); foreach (string name in excludes) { cs.ExcludeList.Add(name.Trim().ToLower()); } // Fail if fundamental information is still missing if (cs.Server == null) throw new Exception(String.Format("[IRC-Channel-{0}] Invalid configuration for region {1}: server missing", cs.idn, rs.Region)); else if (cs.IrcChannel == null) throw new Exception(String.Format("[IRC-Channel-{0}] Invalid configuration for region {1}: channel missing", cs.idn, rs.Region)); else if (cs.BaseNickname == null) throw new Exception(String.Format("[IRC-Channel-{0}] Invalid configuration for region {1}: nick missing", cs.idn, rs.Region)); else if (cs.User == null) throw new Exception(String.Format("[IRC-Channel-{0}] Invalid configuration for region {1}: user missing", cs.idn, rs.Region)); m_log.InfoFormat("[IRC-Channel-{0}] Configuration for Region {1} is valid", cs.idn, rs.Region); m_log.InfoFormat("[IRC-Channel-{0}] Server = {1}", cs.idn, cs.Server); m_log.InfoFormat("[IRC-Channel-{0}] Channel = {1}", cs.idn, cs.IrcChannel); m_log.InfoFormat("[IRC-Channel-{0}] Port = {1}", cs.idn, cs.Port); m_log.InfoFormat("[IRC-Channel-{0}] Nickname = {1}", cs.idn, cs.BaseNickname); m_log.InfoFormat("[IRC-Channel-{0}] User = {1}", cs.idn, cs.User); // Set the channel state for this region if (cs.RelayChat) { cs.ValidInWorldChannels.Add(0); cs.ValidInWorldChannels.Add(DEBUG_CHANNEL); } if (cs.RelayPrivateChannels) cs.ValidInWorldChannels.Add(cs.RelayChannelOut); rs.cs = Integrate(rs, cs); } // An initialized channel state instance is passed in. If an identical // channel state instance already exists, then the existing instance // is used to replace the supplied value. // If the instance matches with respect to IRC, then the underlying // IRCConnector is assigned to the supplied channel state and the // updated value is returned. // If there is no match, then the supplied instance is completed by // creating and assigning an instance of an IRC connector. private static ChannelState Integrate(RegionState rs, ChannelState p_cs) { ChannelState cs = p_cs; // Check to see if we have an existing server/channel setup that can be used // In the absence of variable substitution this will always resolve to the // same ChannelState instance, and the table will only contains a single // entry, so the performance considerations for the existing behavior are // zero. Only the IRC connector is shared, the ChannelState still contains // values that, while independent of the IRC connetion, do still distinguish // this region's behavior. lock (IRCBridgeModule.m_channels) { foreach (ChannelState xcs in IRCBridgeModule.m_channels) { if (cs.IsAPerfectMatchFor(xcs)) { m_log.DebugFormat("[IRC-Channel-{0}] Channel state matched", cs.idn); cs = xcs; break; } if (cs.IsAConnectionMatchFor(xcs)) { m_log.DebugFormat("[IRC-Channel-{0}] Channel matched", cs.idn); cs.irc = xcs.irc; break; } } } // No entry was found, so this is going to be a new entry. if (cs.irc == null) { m_log.DebugFormat("[IRC-Channel-{0}] New channel required", cs.idn); if ((cs.irc = new IRCConnector(cs)) != null) { IRCBridgeModule.m_channels.Add(cs); m_log.InfoFormat("[IRC-Channel-{0}] New channel initialized for {1}, nick: {2}, commands {3}, private channels {4}", cs.idn, rs.Region, cs.DefaultZone, cs.CommandsEnabled ? "enabled" : "not enabled", cs.RelayPrivateChannels ? "relayed" : "not relayed"); } else { string txt = String.Format("[IRC-Channel-{0}] Region {1} failed to connect to channel {2} on server {3}:{4}", cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); m_log.Error(txt); throw new Exception(txt); } } else { m_log.InfoFormat("[IRC-Channel-{0}] Region {1} reusing existing connection to channel {2} on server {3}:{4}", cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); } m_log.InfoFormat("[IRC-Channel-{0}] Region {1} associated with channel {2} on server {3}:{4}", cs.idn, rs.Region, cs.IrcChannel, cs.Server, cs.Port); // We're finally ready to commit ourselves return cs; } // These routines allow differentiating changes to // the underlying channel state. If necessary, a // new channel state will be created. internal ChannelState UpdateServer(RegionState rs, string server) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.Server = server; cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdatePort(RegionState rs, string port) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.Port = Convert.ToUInt32(port); cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdateChannel(RegionState rs, string channel) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.IrcChannel = channel; cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdateNickname(RegionState rs, string nickname) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.BaseNickname = nickname; cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdateClientReporting(RegionState rs, string cr) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.ClientReporting = Convert.ToBoolean(cr); cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdateRelayIn(RegionState rs, string channel) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.RelayChannel = Convert.ToInt32(channel); cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } internal ChannelState UpdateRelayOut(RegionState rs, string channel) { RemoveRegion(rs); ChannelState cs = new ChannelState(this); cs.RelayChannelOut = Convert.ToInt32(channel); cs = Integrate(rs, cs); cs.AddRegion(rs); return cs; } // Determine whether or not this is a 'new' channel. Only those // attributes that uniquely distinguish an IRC connection should // be included here (and only those attributes should really be // in the ChannelState structure) private bool IsAConnectionMatchFor(ChannelState cs) { return ( Server == cs.Server && IrcChannel == cs.IrcChannel && Port == cs.Port && BaseNickname == cs.BaseNickname && User == cs.User ); } // This level of obsessive matching allows us to produce // a minimal overhead int he case of a server which does // need to differentiate IRC at a region level. private bool IsAPerfectMatchFor(ChannelState cs) { return (IsAConnectionMatchFor(cs) && RelayChannelOut == cs.RelayChannelOut && PrivateMessageFormat == cs.PrivateMessageFormat && NoticeMessageFormat == cs.NoticeMessageFormat && RandomizeNickname == cs.RandomizeNickname && AccessPassword == cs.AccessPassword && CommandsEnabled == cs.CommandsEnabled && CommandChannel == cs.CommandChannel && DefaultZone == cs.DefaultZone && RelayPrivateChannels == cs.RelayPrivateChannels && RelayChannel == cs.RelayChannel && RelayChat == cs.RelayChat && ClientReporting == cs.ClientReporting ); } // This function implements the variable substitution mechanism // for the configuration values. Each string read from the // configuration file is scanned for '[...]' enclosures. Each // one that is found is replaced by either a runtime variable // (%xxx) or an existing configuration key. When no further // substitution is possible, the remaining string is returned // to the caller. This allows for arbitrarily nested // enclosures. private static string Substitute(RegionState rs, string instr) { string result = instr; if (string.IsNullOrEmpty(result)) return result; // Repeatedly scan the string until all possible // substitutions have been performed. // m_log.DebugFormat("[IRC-Channel] Parse[1]: {0}", result); while (arg.IsMatch(result)) { string vvar = arg.Match(result).ToString(); string var = vvar.Substring(1, vvar.Length - 2).Trim(); switch (var.ToLower()) { case "%region": result = result.Replace(vvar, rs.Region); break; case "%host": result = result.Replace(vvar, rs.Host); break; case "%locx": result = result.Replace(vvar, rs.LocX); break; case "%locy": result = result.Replace(vvar, rs.LocY); break; case "%k": result = result.Replace(vvar, rs.IDK); break; default: result = result.Replace(vvar, rs.config.GetString(var, var)); break; } // m_log.DebugFormat("[IRC-Channel] Parse[2]: {0}", result); } // m_log.DebugFormat("[IRC-Channel] Parse[3]: {0}", result); return result; } public void Close() { m_log.InfoFormat("[IRC-Channel-{0}] Closing channel <{1}> to server <{2}:{3}>", idn, IrcChannel, Server, Port); m_log.InfoFormat("[IRC-Channel-{0}] There are {1} active clients", idn, clientregions.Count); irc.Close(); } public void Open() { m_log.InfoFormat("[IRC-Channel-{0}] Opening channel <{1}> to server <{2}:{3}>", idn, IrcChannel, Server, Port); irc.Open(); } // These are called by each region that attaches to this channel. The call affects // only the relationship of the region with the channel. Not the channel to IRC // relationship (unless it is closed and we want it open). public void Open(RegionState rs) { AddRegion(rs); Open(); } // Close is called to ensure that the IRC session is terminated if this is the // only client. public void Close(RegionState rs) { RemoveRegion(rs); lock (IRCBridgeModule.m_channels) { if (clientregions.Count == 0) { Close(); IRCBridgeModule.m_channels.Remove(this); m_log.InfoFormat("[IRC-Channel-{0}] Region {1} is last user of channel <{2}> to server <{3}:{4}>", idn, rs.Region, IrcChannel, Server, Port); m_log.InfoFormat("[IRC-Channel-{0}] Removed", idn); } } } // Add a client region to this channel if it is not already known public void AddRegion(RegionState rs) { m_log.InfoFormat("[IRC-Channel-{0}] Adding region {1} to channel <{2}> to server <{3}:{4}>", idn, rs.Region, IrcChannel, Server, Port); if (!clientregions.Contains(rs)) { clientregions.Add(rs); lock (irc) irc.depends++; } } // Remove a client region from the channel. If this is the last // region, then clean up the channel. The connector will clean itself // up if it finds itself about to be GC'd. public void RemoveRegion(RegionState rs) { m_log.InfoFormat("[IRC-Channel-{0}] Removing region {1} from channel <{2} to server <{3}:{4}>", idn, rs.Region, IrcChannel, Server, Port); if (clientregions.Contains(rs)) { clientregions.Remove(rs); lock (irc) irc.depends--; } } // This function is lifted from the IRCConnector because it // contains information that is not differentiating from an // IRC point-of-view. public static void OSChat(IRCConnector p_irc, OSChatMessage c, bool cmsg) { // m_log.DebugFormat("[IRC-OSCHAT] from {0}:{1}", p_irc.Server, p_irc.IrcChannel); try { // Scan through the set of unique channel configuration for those // that belong to this connector. And then forward the message to // all regions known to those channels. // Note that this code is responsible for completing some of the // settings for the inbound OSChatMessage lock (IRCBridgeModule.m_channels) { foreach (ChannelState cs in IRCBridgeModule.m_channels) { if (p_irc == cs.irc) { // This non-IRC differentiator moved to here if (cmsg && !cs.ClientReporting) continue; // This non-IRC differentiator moved to here c.Channel = (cs.RelayPrivateChannels ? cs.RelayChannel : 0); foreach (RegionState region in cs.clientregions) { region.OSChat(cs.irc, c); } } } } } catch (Exception ex) { m_log.ErrorFormat("[IRC-OSCHAT]: BroadcastSim Exception: {0}", ex.Message); m_log.Debug(ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using iSukces.Code; using iSukces.Code.Ammy; using iSukces.Code.AutoCode; using iSukces.Code.Compatibility.System.Windows.Data; using iSukces.Code.Interfaces; namespace AutoCodeBuilder { internal class FluentBindGenerator : BaseGenerator, IAutoCodeGenerator { static FluentBindGenerator() { BindingParams = CreateBindingParams(); MultiBindingParams = CreateMultiBindingParams(); } public static bool IgnoreWithConverterStatic(Type type) => type == typeof(AmmyBind) || type == typeof(AmmyBindBuilder); private static BindingParamInfoCollection CreateBindingParams() { var result = new BindingParamInfoCollection(); AddCommon(result); result.Add<bool>("BindsDirectlyToSource"); result.Add<bool>("IsAsync"); result.Add<string>("XPath", true); result.Add<object>("From", true); result.Add<string>("Path"); return result; } private static void AddCommon(BindingParamInfoCollection result) { result.Add<XBindingMode>("Mode"); result.Add<object>("Converter", true); result.Add<object>("ConverterCulture", true); result.Add<object>("ConverterParameter", true); result.Add<XUpdateSourceTrigger>("UpdateSourceTrigger"); result.Add<bool>("NotifyOnSourceUpdated"); result.Add<bool>("NotifyOnTargetUpdated"); result.Add<bool>("NotifyOnValidationError"); result.Add<object>(ValidationRules); result.Add<bool>("ValidatesOnExceptions"); result.Add<bool>("ValidatesOnDataErrors"); result.Add<bool>("ValidatesOnNotifyDataErrors"); result.Add<string>("StringFormat"); result.Add<string>("BindingGroupName"); result.Add<object>("TargetNullValue"); } private static BindingParamInfoCollection CreateMultiBindingParams() { var result = new BindingParamInfoCollection(); AddCommon(result); result.Add<List<object>>("Bindings"); return result; } private static Type MakeNullable(Type type) => type.IsValueType ? typeof(Nullable<>).MakeGenericType(type) : type; private static string SetPropertyAndReturnThis(string propertyName, string value) => $"{propertyName} = {value}; return this;"; private static IEnumerable<string> SplitEnumerable(string text) { if (string.IsNullOrEmpty(text)) return new string[0]; return text.Split('\r', '\n').Select(a => a.Trim()).Where(a => !string.IsNullOrEmpty(a)); } public void Generate(Type type, IAutoCodeGeneratorContext context) { if (type == typeof(AmmyBind)) { _currentClass = context.GetOrCreateClass(type); foreach (var i in BindingParams) { var fl = i.GetFlags(type); AddFluentMethod( (paramName, argName) => { if (i.HasProperty(type)) return SetPropertyAndReturnThis(paramName, argName); return $"return WithSetParameter({paramName.CsEncode()}, {argName});"; }, i.Type, i.PropertyName, fl); } } else if (type == typeof(AmmyBindBuilder)) { BuildPropertiesAndFluentMethods(context, type, BindingParams, typeof(AmmyBind)); } else if (type == typeof(XMultiBinding)) { BuildPropertiesAndFluentMethods(context, type, MultiBindingParams, null, false); } else if (type == typeof(AmmyMultiBindingBuilder)) { BuildPropertiesAndFluentMethods(context, type, MultiBindingParams, typeof(AmmyMultiBind)); } else if (type == typeof(AmmyMultiBind)) { BuildPropertiesAndFluentMethods(context, type, MultiBindingParams, null); } } private void AddFluentMethod(Func<string, string, string> creator, Type type, string paramName, Fl flags) { void AddStaticAndResource(FluentMethodInfo mi) { { const string argName = "propertyName"; var value = $"new StaticBindingSource(typeof(TStaticPropertyOwner), {argName})"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); _currentClass.AddMethod(mi.Static + "<TStaticPropertyOwner>", _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass) .AddParam<string>(argName, _currentClass); } { const string argName = "staticResourceName"; var value = $"new {nameof(AmmyStaticResource)}({argName})"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); _currentClass.AddMethod(mi.StaticResource, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass /*code.Info*/) .AddParam<string>(argName, _currentClass); } { const string argName = "dynamicResourceName"; var value = $"new {nameof(AmmyDynamicResource)}({argName})"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); _currentClass.AddMethod(mi.DynamicResource, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass) .AddParam<string>(argName, _currentClass); } { const string argName = "elementName"; var value = $"new {nameof(ElementNameBindingSource)}({argName})"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); _currentClass.AddMethod(mi.ElementName, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass) .AddParam<string>(argName, _currentClass); } } void AddSelf(FluentMethodInfo mi) { const string value = nameof(SelfBindingSource) + "." + nameof(SelfBindingSource.Instance); { var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); var m = _currentClass.AddMethod(mi.Self, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass /*code.Info*/); } /*{ //var name = CodeUtils.GetMemberPath(func); // this.WithProperty(name, value); var code = CreateCodeWriter() .WriteLine("var name = CodeUtils.GetMemberPath(func);") .WriteLine("this.WithProperty(name, value);") .WriteLine(creator(paramName, value)); var m = _currentClass.AddMethod(mi.Self+"<TPropertyBrowser>", _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass /*code.Info#1#); m.AddParam("ancestorType", "Expression<Func<TPropertyBrowser, TValue>> func"); }*/ } void AddAncestor(FluentMethodInfo mi) { { const string value = "new AncestorBindingSource(ancestorType, level)"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); var m = _currentClass.AddMethod(mi.Ancestor, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass /*code.Info*/); m.AddParam<Type>("ancestorType", _currentClass); m.AddParam<int?>("level", _currentClass).WithConstValueNull(); } { var methodName = mi.Ancestor + "<TAncestor>"; const string value = "new AncestorBindingSource(typeof(TAncestor), level)"; var code = CreateCodeWriter() .WriteLine(creator(paramName, value)); var m = _currentClass.AddMethod(methodName, _currentClass.Name) .WithBody(code) .WithAutocodeGeneratedAttribute(_currentClass /*code.Info*/); m.AddParam<int?>("level", _currentClass).WithConstValueNull(); } } void AddDirectValue(Type type1, FluentMethodInfo flu1) { var argName = paramName.FirstLower(); var body = CreateCodeWriter() .WriteLine(creator(paramName, argName)); var m = _currentClass.AddMethod(flu1.FluentPrefix, _currentClass.Name) .WithBody(body); m.AddParam(argName, _currentClass.TypeName(type1)); m.WithAutocodeGeneratedAttribute(_currentClass /*body.Info*/); } var flu = new FluentMethodInfo(paramName); if ((flags & Fl.DirectValue) != 0) { AddDirectValue(type, flu); if ((flags & Fl.AddObjectOverload) != 0 && type != typeof(object)) AddDirectValue(typeof(object), flu); } if ((flags & Fl.AddStaticAndResource) != 0) AddStaticAndResource(flu); if (flu.AllowAncestor) { AddAncestor(flu); AddSelf(flu); } } private void BuildPropertiesAndFluentMethods(IAutoCodeGeneratorContext context, Type ownerType, List<BindingParamInfo> bindingParams, Type setup, bool addFluetMethods=true) { _currentClass = context.GetOrCreateClass(ownerType); var setupCode = CreateCodeWriter(); foreach (var i in bindingParams) { var flu = new FluentMethodInfo(i.PropertyName); var type2 = i.Type; string init = null; var isReadOnly = false; if (i.PropertyName == ValidationRules) { type2 = typeof(List<object>); init = "new " + _currentClass.TypeName(type2) + "()"; isReadOnly = true; } else { type2 = MakeNullable(type2); setupCode.SingleLineIf( $"{i.PropertyName} != null", $"bind.{flu.FluentPrefix}({i.PropertyName});"); } bool CreateProperty() { var pi = ownerType.GetProperty(i.PropertyName); if (pi is null) return true; return !(pi.GetCustomAttribute<AutocodeGeneratedAttribute>() is null); } if (CreateProperty()) { var p = _currentClass.AddProperty(i.PropertyName, type2) .WithNoEmitField() .WithMakeAutoImplementIfPossible() .WithIsPropertyReadOnly(isReadOnly) .WithAutocodeGeneratedAttribute(_currentClass); p.ConstValue = init; } if (!isReadOnly && addFluetMethods) { var fl = i.GetFlags(ownerType); AddFluentMethod( SetPropertyAndReturnThis, type2, i.PropertyName, fl); } } if (setup != null) _currentClass.AddMethod("SetupAmmyBind", "void") .WithVisibility(Visibilities.Private) .WithBody(setupCode) .WithAutocodeGeneratedAttribute(_currentClass /*setupCode.Info*/) .AddParam("bind", setup, _currentClass); } private static readonly BindingParamInfoCollection BindingParams; private static readonly BindingParamInfoCollection MultiBindingParams; private CsClass _currentClass; [Flags] private enum Fl { None = 0, DirectValue = 1, AddObjectOverload = 2, AddStaticAndResource = 4 } private const string ValidationRules = "ValidationRules"; private class BindingParamInfoCollection : List<BindingParamInfo> { public void Add<T>(string name, bool bindableToStaticOrResource = false) { var a = new BindingParamInfo(typeof(T), name, bindableToStaticOrResource); Add(a); } } private class BindingParamInfo { public BindingParamInfo(Type type, string propertyName, bool bindableToStaticOrResource = false) { Type = type; PropertyName = propertyName; BindableToStaticOrResource = bindableToStaticOrResource; } public Fl GetFlags(Type ownerType) { // var fl = BindableToStaticOrResource ? Fl.AddStaticAndResource : Fl.None; var flags = Fl.DirectValue; { var p = ownerType.GetProperty(PropertyName); if (p is null) { flags |= Fl.AddObjectOverload; if (BindableToStaticOrResource) flags |= Fl.AddStaticAndResource; } else { if (p.PropertyType == typeof(object)) flags |= Fl.AddObjectOverload | Fl.AddStaticAndResource; } } return flags; } public bool HasProperty(Type ownerType) { var p = ownerType.GetProperty(PropertyName); return p != null; } public override string ToString() => PropertyName; public Type Type { get; } public string PropertyName { get; } /// <summary> /// If Binding object has this property bindable /// </summary> public bool BindableToStaticOrResource { get; } } } }
using System; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium { [TestFixture] public class ClickTest : DriverTestFixture { [SetUp] public void SetupMethod() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("clicks.html"); } [TearDown] public void TearDownMethod() { driver.SwitchTo().DefaultContent(); } [Test] public void CanClickOnALinkAndFollowIt() { driver.FindElement(By.Id("normal")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] [IgnoreBrowser(Browser.Opera, "Not tested")] public void CanClickOnALinkThatOverflowsAndFollowIt() { driver.FindElement(By.Id("overflowLink")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); } [Test] public void CanClickOnAnAnchorAndNotReloadThePage() { ((IJavaScriptExecutor)driver).ExecuteScript("document.latch = true"); driver.FindElement(By.Id("anchor")).Click(); bool samePage = (bool)((IJavaScriptExecutor)driver).ExecuteScript("return document.latch"); Assert.AreEqual(true, samePage, "Latch was reset"); } [Test] public void CanClickOnALinkThatUpdatesAnotherFrame() { driver.SwitchTo().Frame("source"); driver.FindElement(By.Id("otherframe")).Click(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); Assert.That(driver.PageSource, Does.Contain("Hello WebDriver")); } [Test] public void ElementsFoundByJsCanLoadUpdatesInAnotherFrame() { driver.SwitchTo().Frame("source"); IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');"); toClick.Click(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); Assert.That(driver.PageSource, Does.Contain("Hello WebDriver")); } [Test] public void JsLocatedElementsCanUpdateFramesIfFoundSomehowElse() { driver.SwitchTo().Frame("source"); // Prime the cache of elements driver.FindElement(By.Id("otherframe")); // This _should_ return the same element IWebElement toClick = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("return document.getElementById('otherframe');"); toClick.Click(); driver.SwitchTo().DefaultContent().SwitchTo().Frame("target"); Assert.That(driver.PageSource, Does.Contain("Hello WebDriver")); } [Test] public void CanClickOnAnElementWithTopSetToANegativeNumber() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("styledPage.html"); IWebElement searchBox = driver.FindElement(By.Name("searchBox")); searchBox.SendKeys("Cheese"); driver.FindElement(By.Name("btn")).Click(); string log = driver.FindElement(By.Id("log")).Text; Assert.AreEqual("click", log); } [Test] [IgnoreBrowser(Browser.Opera)] public void ShouldSetRelatedTargetForMouseOver() { driver.Url = javascriptPage; driver.FindElement(By.Id("movable")).Click(); string log = driver.FindElement(By.Id("result")).Text; // Note: It is not guaranteed that the relatedTarget property of the mouseover // event will be the parent, when using native events. Only check that the mouse // has moved to this element, not that the parent element was the related target. if (this.IsNativeEventsEnabled) { Assert.That(log, Does.StartWith("parent matches?")); } else { Assert.AreEqual("parent matches? true", log); } } [Test] public void ShouldClickOnFirstBoundingClientRectWithNonZeroSize() { driver.FindElement(By.Id("twoClientRects")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] [NeedsFreshDriver(IsCreatedAfterTest = true)] [IgnoreBrowser(Browser.Opera, "Doesn't support multiple windows")] public void ShouldOnlyFollowHrefOnce() { driver.Url = clicksPage; int windowHandlesBefore = driver.WindowHandles.Count; driver.FindElement(By.Id("new-window")).Click(); WaitFor(() => { return driver.WindowHandles.Count >= windowHandlesBefore + 1; }, "Window handles was not " + (windowHandlesBefore + 1).ToString()); Assert.AreEqual(windowHandlesBefore + 1, driver.WindowHandles.Count); } [Test] [Ignore("Ignored for all browsers")] public void ShouldSetRelatedTargetForMouseOut() { Assert.Fail("Must. Write. Meamingful. Test (but we don't fire mouse outs synthetically"); } [Test] public void ClickingLabelShouldSetCheckbox() { driver.Url = formsPage; driver.FindElement(By.Id("label-for-checkbox-with-label")).Click(); Assert.That(driver.FindElement(By.Id("checkbox-with-label")).Selected, "Checkbox should be selected"); } [Test] public void CanClickOnALinkWithEnclosedImage() { driver.FindElement(By.Id("link-with-enclosed-image")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void CanClickOnAnImageEnclosedInALink() { driver.FindElement(By.Id("link-with-enclosed-image")).FindElement(By.TagName("img")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void CanClickOnALinkThatContainsTextWrappedInASpan() { driver.FindElement(By.Id("link-with-enclosed-span")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void CanClickOnALinkThatContainsEmbeddedBlockElements() { driver.FindElement(By.Id("embeddedBlock")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void CanClickOnAnElementEnclosedInALink() { driver.FindElement(By.Id("link-with-enclosed-span")).FindElement(By.TagName("span")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } // See http://code.google.com/p/selenium/issues/attachmentText?id=2700 [Test] public void ShouldBeAbleToClickOnAnElementInTheViewport() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_out_of_bounds.html"); driver.Url = url; IWebElement button = driver.FindElement(By.Id("button")); button.Click(); } [Test] public void ClicksASurroundingStrongTag() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("ClickTest_testClicksASurroundingStrongTag.html"); driver.FindElement(By.TagName("a")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); } [Test] [IgnoreBrowser(Browser.Opera, "Map click fails")] public void CanClickAnImageMapArea() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html"); driver.FindElement(By.Id("rectG")).Click(); WaitFor(() => { return driver.Title == "Target Page 1"; }, "Browser title was not 'Target Page 1'"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html"); driver.FindElement(By.Id("circleO")).Click(); WaitFor(() => { return driver.Title == "Target Page 2"; }, "Browser title was not 'Target Page 2'"); driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/google_map.html"); driver.FindElement(By.Id("polyLE")).Click(); WaitFor(() => { return driver.Title == "Target Page 3"; }, "Browser title was not 'Target Page 3'"); } [Test] public void ShouldBeAbleToClickOnAnElementGreaterThanTwoViewports() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("click")); element.Click(); WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'"); } [Test] [IgnoreBrowser(Browser.Opera, "Not Tested")] public void ShouldBeAbleToClickOnAnElementInFrameGreaterThanTwoViewports() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_too_big_in_frame.html"); driver.Url = url; IWebElement frame = driver.FindElement(By.Id("iframe1")); driver.SwitchTo().Frame(frame); IWebElement element = driver.FindElement(By.Id("click")); element.Click(); WaitFor(() => { return driver.Title == "clicks"; }, "Browser title was not 'clicks'"); } [Test] public void ShouldBeAbleToClickOnRightToLeftLanguageLink() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_rtl.html"); driver.Url = url; IWebElement element = driver.FindElement(By.Id("ar_link")); element.Click(); WaitFor(() => driver.Title == "clicks", "Expected title to be 'clicks'"); Assert.AreEqual("clicks", driver.Title); } [Test] public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooter() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScroll.html"); driver.Url = url; driver.FindElement(By.Id("link")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void ShouldBeAbleToClickOnLinkInAbsolutelyPositionedFooterInQuirksMode() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("fixedFooterNoScrollQuirksMode.html"); driver.Url = url; driver.FindElement(By.Id("link")).Click(); WaitFor(() => { return driver.Title == "XHTML Test Page"; }, "Browser title was not 'XHTML Test Page'"); Assert.AreEqual("XHTML Test Page", driver.Title); } [Test] public void ShouldBeAbleToClickOnLinksWithNoHrefAttribute() { driver.Url = javascriptPage; IWebElement element = driver.FindElement(By.LinkText("No href")); element.Click(); WaitFor(() => driver.Title == "Changed", "Expected title to be 'Changed'"); Assert.AreEqual("Changed", driver.Title); } [Test] public void ShouldBeAbleToClickOnALinkThatWrapsToTheNextLine() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/link_that_wraps.html"); driver.FindElement(By.Id("link")).Click(); WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'"); Assert.AreEqual("Submitted Successfully!", driver.Title); } [Test] public void ShouldBeAbleToClickOnASpanThatWrapsToTheNextLine() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/span_that_wraps.html"); driver.FindElement(By.Id("span")).Click(); WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'"); Assert.AreEqual("Submitted Successfully!", driver.Title); } [Test] [IgnoreBrowser(Browser.IE, "Element is properly seen as obscured.")] [IgnoreBrowser(Browser.Chrome, "Element is properly seen as obscured.")] [IgnoreBrowser(Browser.Edge, "Element is properly seen as obscured.")] [IgnoreBrowser(Browser.EdgeLegacy, "Element is properly seen as obscured.")] [IgnoreBrowser(Browser.Firefox, "Element is properly seen as obscured.")] [IgnoreBrowser(Browser.Safari, "Element is properly seen as obscured.")] public void ShouldBeAbleToClickOnAPartiallyOverlappedLinkThatWrapsToTheNextLine() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/wrapped_overlapping_elements.html"); driver.FindElement(By.Id("link")).Click(); WaitFor(() => driver.Title == "Submitted Successfully!", "Expected title to be 'Submitted Successfully!'"); Assert.AreEqual("Submitted Successfully!", driver.Title); } [Test] public void ClickingOnADisabledElementIsANoOp() { driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("click_tests/disabled_element.html"); IWebElement element = driver.FindElement(By.Name("disabled")); element.Click(); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public void ShouldBeAbleToClickLinkContainingLineBreak() { driver.Url = simpleTestPage; driver.FindElement(By.Id("multilinelink")).Click(); WaitFor(() => { return driver.Title == "We Arrive Here"; }, "Browser title was not 'We Arrive Here'"); Assert.AreEqual("We Arrive Here", driver.Title); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Threading; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using Apache.Geode.DUnitFramework; using Apache.Geode.Client.Tests; using Apache.Geode.Client; //using Region = Apache.Geode.Client.IRegion<Object, Object>; using AssertionException = Apache.Geode.Client.AssertionException; public abstract class ThinClientSecurityAuthzTestBase : ThinClientRegionSteps { #region Protected members protected const string SubregionName = "AuthSubregion"; protected const string CacheXml1 = "cacheserver_notify_subscription.xml"; protected const string CacheXml2 = "cacheserver_notify_subscription2.xml"; #endregion #region Private methods private static string IndicesToString(int[] indices) { string str = string.Empty; if (indices != null && indices.Length > 0) { str += indices[0]; for (int index = 1; index < indices.Length; ++index) { str += ','; str += indices[index]; } } return str; } private IRegion<TKey, TValue> CreateSubregion<TKey, TValue>(IRegion<TKey, TValue> region) { Util.Log("CreateSubregion " + SubregionName); IRegion<TKey, TValue> subregion = region.GetSubRegion(SubregionName); if (subregion == null) { //subregion = region.CreateSubRegion(SubregionName, region.Attributes); subregion = CacheHelper.GetRegion<TKey, TValue>(region.FullPath).CreateSubRegion(SubregionName, region.Attributes); } return subregion; } private bool CheckFlags(OpFlags flags, OpFlags checkFlag) { return ((flags & checkFlag) == checkFlag); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult) { DoOp(op, indices, flags, expectedResult, null, false); } protected void DoOp(OperationCode op, int[] indices, OpFlags flags, ExpectedResult expectedResult, Properties<string, string> creds, bool isMultiuser) { IRegion<object, object> region; if(isMultiuser) region = CacheHelper.GetRegion<object, object>(RegionName, creds); else region = CacheHelper.GetRegion<object, object>(RegionName); if (CheckFlags(flags, OpFlags.UseSubRegion)) { IRegion<object, object> subregion = null; if (CheckFlags(flags, OpFlags.NoCreateSubRegion)) { subregion = region.GetSubRegion(SubregionName); if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(subregion); return; } else { Assert.IsNotNull(subregion); } } else { subregion = CreateSubregion(region); if (isMultiuser) subregion = region.GetSubRegion(SubregionName); } Assert.IsNotNull(subregion); region = subregion; } else if (CheckFlags(flags, OpFlags.CheckNoRegion)) { Assert.IsNull(region); return; } else { Assert.IsNotNull(region); } string valPrefix; if (CheckFlags(flags, OpFlags.UseNewVal)) { valPrefix = NValuePrefix; } else { valPrefix = ValuePrefix; } int numOps = indices.Length; Util.Log("Got DoOp for op: " + op + ", numOps: " + numOps + ", indices: " + IndicesToString(indices)); bool exceptionOccured = false; bool breakLoop = false; for (int indexIndex = 0; indexIndex < indices.Length; ++indexIndex) { if (breakLoop) { break; } int index = indices[indexIndex]; string key = KeyPrefix + index; string expectedValue = (valPrefix + index); try { switch (op) { case OperationCode.Get: Object value = null; if (CheckFlags(flags, OpFlags.LocalOp)) { int sleepMillis = 100; int numTries = 30; bool success = false; while (!success && numTries-- > 0) { if (!isMultiuser && region.ContainsValueForKey(key)) { value = region[key]; success = expectedValue.Equals(value.ToString()); if (CheckFlags(flags, OpFlags.CheckFail)) { success = !success; } } else { value = null; success = CheckFlags(flags, OpFlags.CheckFail); } if (!success) { Thread.Sleep(sleepMillis); } } } else { if (!isMultiuser) { if (CheckFlags(flags, OpFlags.CheckNoKey)) { Assert.IsFalse(region.GetLocalView().ContainsKey(key)); } else { Assert.IsTrue(region.GetLocalView().ContainsKey(key)); region.GetLocalView().Invalidate(key); } } try { value = region[key]; } catch (Client.KeyNotFoundException ) { Util.Log("KeyNotFoundException while getting key. should be ok as we are just testing auth"); } } if (!isMultiuser && value != null) { if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreNotEqual(expectedValue, value.ToString()); } else { Assert.AreEqual(expectedValue, value.ToString()); } } break; case OperationCode.Put: region[key] = expectedValue; break; case OperationCode.Destroy: if (!isMultiuser && !region.GetLocalView().ContainsKey(key)) { // Since DESTROY will fail unless the value is present // in the local cache, this is a workaround for two cases: // 1. When the operation is supposed to succeed then in // the current AuthzCredentialGenerators the clients having // DESTROY permission also has CREATE/UPDATE permission // so that calling region.Put() will work for that case. // 2. When the operation is supposed to fail with // NotAuthorizedException then in the current // AuthzCredentialGenerators the clients not // having DESTROY permission are those with reader role that have // GET permission. // // If either of these assumptions fails, then this has to be // adjusted or reworked accordingly. if (CheckFlags(flags, OpFlags.CheckNotAuthz)) { value = region[key]; Assert.AreEqual(expectedValue, value.ToString()); } else { region[key] = expectedValue; } } if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().Remove(key); //Destroyed replaced by Remove() API } else { region.Remove(key); //Destroyed replaced by Remove API } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.RegisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().RegisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().RegisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().RegisterAllKeys(); } break; //TODO: Need to fix Stack overflow exception.. case OperationCode.UnregisterInterest: if (CheckFlags(flags, OpFlags.UseList)) { breakLoop = true; // Register interest list in this case List<CacheableKey> keyList = new List<CacheableKey>(numOps); for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; keyList.Add(KeyPrefix + keyNum); } region.GetSubscriptionService().UnregisterKeys(keyList.ToArray()); } else if (CheckFlags(flags, OpFlags.UseRegex)) { breakLoop = true; region.GetSubscriptionService().UnregisterRegex(KeyPrefix + "[0-" + (numOps - 1) + ']'); } else if (CheckFlags(flags, OpFlags.UseAllKeys)) { breakLoop = true; region.GetSubscriptionService().UnregisterAllKeys(); } break; case OperationCode.Query: breakLoop = true; ISelectResults<object> queryResults; if (!isMultiuser) { queryResults = (ResultSet<object>)region.Query<object>( "SELECT DISTINCT * FROM " + region.FullPath); } else { queryResults = CacheHelper.getMultiuserCache(creds).GetQueryService<object, object>().NewQuery("SELECT DISTINCT * FROM " + region.FullPath).Execute(); } Assert.IsNotNull(queryResults); if (!CheckFlags(flags, OpFlags.CheckFail)) { Assert.AreEqual(numOps, queryResults.Size); } //CacheableHashSet querySet = new CacheableHashSet(queryResults.Size); List<string> querySet = new List<string>(queryResults.Size); ResultSet<object> rs = queryResults as ResultSet<object>; foreach ( object result in rs) { querySet.Add(result.ToString()); } for (int keyNumIndex = 0; keyNumIndex < numOps; ++keyNumIndex) { int keyNum = indices[keyNumIndex]; string expectedVal = valPrefix + keyNumIndex; if (CheckFlags(flags, OpFlags.CheckFail)) { Assert.IsFalse(querySet.Contains(expectedVal)); } else { Assert.IsTrue(querySet.Contains(expectedVal)); } } break; case OperationCode.RegionDestroy: breakLoop = true; if ( !isMultiuser && CheckFlags(flags, OpFlags.LocalOp)) { region.GetLocalView().DestroyRegion(); } else { region.DestroyRegion(); } break; case OperationCode.GetServerKeys: breakLoop = true; ICollection<object> serverKeys = region.Keys; break; //TODO: Need to fix System.ArgumentOutOfRangeException: Index was out of range. Know issue with GetAll() case OperationCode.GetAll: //ICacheableKey[] keymap = new ICacheableKey[5]; List<object> keymap = new List<object>(); for (int i = 0; i < 5; i++) { keymap.Add(i); //CacheableInt32 item = CacheableInt32.Create(i); //Int32 item = i; // NOTE: GetAll should operate right after PutAll //keymap[i] = item; } Dictionary<Object, Object> entrymap = new Dictionary<Object, Object>(); //CacheableHashMap entrymap = CacheableHashMap.Create(); region.GetAll(keymap, entrymap, null, false); if (entrymap.Count < 5) { Assert.Fail("DoOp: Got fewer entries for op " + op); } break; case OperationCode.PutAll: // NOTE: PutAll should operate right before GetAll //CacheableHashMap entrymap2 = CacheableHashMap.Create(); Dictionary<Object, Object> entrymap2 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap2.Add(item, item); } region.PutAll(entrymap2); break; case OperationCode.RemoveAll: Dictionary<Object, Object> entrymap3 = new Dictionary<object, object>(); for (int i = 0; i < 5; i++) { //CacheableInt32 item = CacheableInt32.Create(i); Int32 item = i; entrymap3.Add(item, item); } region.PutAll(entrymap3); ICollection<object> keys = new LinkedList<object>(); for (int i = 0; i < 5; i++) { Int32 item = i; keys.Add(item); } region.RemoveAll(keys); break; case OperationCode.ExecuteCQ: Pool/*<object, object>*/ pool = PoolManager/*<object, object>*/.Find("__TESTPOOL1_"); QueryService<object, object> qs; if (pool != null) { qs = pool.GetQueryService<object, object>(); } else { //qs = CacheHelper.DCache.GetQueryService<object, object>(); qs = null; } CqAttributesFactory<object, object> cqattrsfact = new CqAttributesFactory<object, object>(); CqAttributes<object, object> cqattrs = cqattrsfact.Create(); CqQuery<object, object> cq = qs.NewCq("cq_security", "SELECT * FROM /" + region.Name, cqattrs, false); qs.ExecuteCqs(); qs.StopCqs(); qs.CloseCqs(); break; case OperationCode.ExecuteFunction: if (!isMultiuser) { Pool/*<object, object>*/ pool2 = PoolManager/*<object, object>*/.Find("__TESTPOOL1_"); if (pool2 != null) { Client.FunctionService<object>.OnServer(pool2).Execute("securityTest"); Client.FunctionService<object>.OnRegion<object, object>(region).Execute("FireNForget"); } else { expectedResult = ExpectedResult.Success; } } else { //FunctionService fs = CacheHelper.getMultiuserCache(creds).GetFunctionService(); //Execution exe = fs.OnServer(); IRegionService userCache = CacheHelper.getMultiuserCache(creds); Apache.Geode.Client.Execution<object> exe = Client.FunctionService<object>.OnServer(userCache); exe.Execute("securityTest"); exe = Client.FunctionService<object>.OnServers(userCache); Client.FunctionService<object>.OnRegion<object, object>(region); Client.FunctionService<object>.OnRegion<object, object>(userCache.GetRegion<object, object>(region.Name)).Execute("FireNForget"); } break; default: Assert.Fail("DoOp: Unhandled operation " + op); break; } if (expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } } catch (AssertionException ex) { Util.Log("DoOp: failed assertion: {0}", ex); throw; } catch (NotAuthorizedException ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.NotAuthorizedException) { Util.Log( "DoOp: Got expected NotAuthorizedException when doing operation [" + op + "] with flags [" + flags + "]: " + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected NotAuthorizedException when " + "doing operation: " + ex.Message); } } catch (Exception ex) { exceptionOccured = true; if (expectedResult == ExpectedResult.OtherException) { Util.Log("DoOp: Got expected exception when doing operation: " + ex.GetType() + "::" + ex.Message); continue; } else { Assert.Fail("DoOp: Got unexpected exception when doing operation: " + ex); } } } if (!exceptionOccured && expectedResult != ExpectedResult.Success) { Assert.Fail("Expected an exception while performing operation"); } Util.Log(" doop done"); } protected void ExecuteOpBlock(List<OperationWithAction> opBlock, string authInit, Properties<string, string> extraAuthProps, Properties<string, string> extraAuthzProps, TestCredentialGenerator gen, Random rnd, bool isMultiuser, bool ssl,bool withPassword) { foreach (OperationWithAction currentOp in opBlock) { // Start client with valid credentials as specified in // OperationWithAction OperationCode opCode = currentOp.OpCode; OpFlags opFlags = currentOp.Flags; int clientNum = currentOp.ClientNum; if (clientNum > m_clients.Length) { Assert.Fail("ExecuteOpBlock: Unknown client number " + clientNum); } ClientBase client = m_clients[clientNum - 1]; Util.Log("ExecuteOpBlock: performing operation number [" + currentOp.OpNum + "]: " + currentOp); Properties<string, string> clientProps = null; if (!CheckFlags(opFlags, OpFlags.UseOldConn)) { Properties<string, string> opCredentials; int newRnd = rnd.Next(100) + 1; string currentRegionName = '/' + RegionName; if (CheckFlags(opFlags, OpFlags.UseSubRegion)) { currentRegionName += ('/' + SubregionName); } string credentialsTypeStr; OperationCode authOpCode = currentOp.AuthzOperationCode; int[] indices = currentOp.Indices; CredentialGenerator cGen = gen.GetCredentialGenerator(); Properties<string, string> javaProps = null; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz) || CheckFlags(opFlags, OpFlags.UseNotAuthz)) { opCredentials = gen.GetDisallowedCredentials( new OperationCode[] { authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " unauthorized " + authOpCode; } else { opCredentials = gen.GetAllowedCredentials(new OperationCode[] { opCode, authOpCode }, new string[] { currentRegionName }, indices, newRnd); credentialsTypeStr = " authorized " + authOpCode; } if (cGen != null) { javaProps = cGen.JavaProperties; } clientProps = SecurityTestUtil.ConcatProperties( opCredentials, extraAuthProps, extraAuthzProps); // Start the client with valid credentials but allowed or disallowed to // perform an operation Util.Log("ExecuteOpBlock: For client" + clientNum + credentialsTypeStr + " credentials: " + opCredentials); if(!isMultiuser) client.Call(SecurityTestUtil.CreateClientSSL, RegionName, CacheHelper.Locators, authInit, clientProps, ssl, withPassword); else client.Call(SecurityTestUtil.CreateClientMU, RegionName, CacheHelper.Locators, authInit, (Properties<string, string>)null, true); } ExpectedResult expectedResult; if (CheckFlags(opFlags, OpFlags.CheckNotAuthz)) { expectedResult = ExpectedResult.NotAuthorizedException; } else if (CheckFlags(opFlags, OpFlags.CheckException)) { expectedResult = ExpectedResult.OtherException; } else { expectedResult = ExpectedResult.Success; } // Perform the operation from selected client if (!isMultiuser) client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult); else client.Call(DoOp, opCode, currentOp.Indices, opFlags, expectedResult, clientProps, true); } } protected List<AuthzCredentialGenerator> GetAllGeneratorCombos(bool isMultiUser) { List<AuthzCredentialGenerator> generators = new List<AuthzCredentialGenerator>(); foreach (AuthzCredentialGenerator.ClassCode authzClassCode in Enum.GetValues(typeof(AuthzCredentialGenerator.ClassCode))) { List<CredentialGenerator> cGenerators = SecurityTestUtil.getAllGenerators(isMultiUser); foreach (CredentialGenerator cGen in cGenerators) { AuthzCredentialGenerator authzGen = AuthzCredentialGenerator .Create(authzClassCode); if (authzGen != null) { if (authzGen.Init(cGen)) { generators.Add(authzGen); } } } } return generators; } protected void RunOpsWithFailoverSSL(OperationWithAction[] opCodes, string testName, bool withPassword) { RunOpsWithFailover(opCodes, testName, false, true,withPassword); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName) { RunOpsWithFailover(opCodes, testName, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser) { RunOpsWithFailover(opCodes, testName, isMultiUser, false, false); } protected void RunOpsWithFailover(OperationWithAction[] opCodes, string testName, bool isMultiUser, bool ssl, bool withPassword) { CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2); CacheHelper.StartJavaLocator(1, "GFELOC", null, ssl); Util.Log("Locator started"); foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(isMultiUser)) { CredentialGenerator cGen = authzGen.GetCredentialGenerator(); Properties<string, string> extraAuthProps = cGen.SystemProperties; Properties<string, string> javaProps = cGen.JavaProperties; Properties<string, string> extraAuthzProps = authzGen.SystemProperties; string authenticator = cGen.Authenticator; string authInit = cGen.AuthInit; string accessor = authzGen.AccessControl; TestAuthzCredentialGenerator tgen = new TestAuthzCredentialGenerator(authzGen); Util.Log(testName + ": Using authinit: " + authInit); Util.Log(testName + ": Using authenticator: " + authenticator); Util.Log(testName + ": Using accessor: " + accessor); // Start servers with all required properties string serverArgs = SecurityTestUtil.GetServerArgs(authenticator, accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps, extraAuthzProps), javaProps); // Perform all the ops on the clients List<OperationWithAction> opBlock = new List<OperationWithAction>(); Random rnd = new Random(); for (int opNum = 0; opNum < opCodes.Length; ++opNum) { // Start client with valid credentials as specified in // OperationWithAction OperationWithAction currentOp = opCodes[opNum]; if (currentOp == OperationWithAction.OpBlockEnd || currentOp == OperationWithAction.OpBlockNoFailover) { // End of current operation block; execute all the operations // on the servers with/without failover if (opBlock.Count > 0) { // Start the first server and execute the operation block CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs, ssl); Util.Log("Cacheserver 1 started."); CacheHelper.StopJavaServer(2, false); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); if (currentOp == OperationWithAction.OpBlockNoFailover) { CacheHelper.StopJavaServer(1); } else { // Failover to the second server and run the block again CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs, ssl); Util.Log("Cacheserver 2 started."); CacheHelper.StopJavaServer(1); ExecuteOpBlock(opBlock, authInit, extraAuthProps, extraAuthzProps, tgen, rnd, isMultiUser, ssl, withPassword); } opBlock.Clear(); } } else { currentOp.OpNum = opNum; opBlock.Add(currentOp); } } // Close all clients here since we run multiple iterations for pool and non pool configs foreach (ClientBase client in m_clients) { client.Call(Close); } } CacheHelper.StopJavaLocator(1, true, ssl); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #endregion /// <summary> /// This class specifies flags that can be used to alter the behaviour of /// operations being performed by the <see cref="DoOp"/> method. /// </summary> [Flags] public enum OpFlags { /// <summary> /// Default behaviour. /// </summary> None = 0x0, /// <summary> /// Check that the operation should fail. /// </summary> CheckFail = 0x1, /// <summary> /// Check that the operation should throw <c>NotAuthorizedException</c>. /// </summary> CheckNotAuthz = 0x2, /// <summary> /// Do the connection with unauthorized credentials but do not check that the /// operation throws <c>NotAuthorizedException</c>. /// </summary> UseNotAuthz = 0x4, /// <summary> /// Check that the region should not be available. /// </summary> CheckNoRegion = 0x8, /// <summary> /// Check that the operation should throw an exception other than the /// <c>NotAuthorizedException</c>. /// </summary> CheckException = 0x10, /// <summary> /// Check for values starting with <c>NValuePrefix</c> instead of /// <c>ValuePrefix</c>. /// </summary> UseNewVal = 0x20, /// <summary> /// Register a regular expression. /// </summary> UseRegex = 0x40, /// <summary> /// Register a list of keys. /// </summary> UseList = 0x80, /// <summary> /// Register all keys. /// </summary> UseAllKeys = 0x100, /// <summary> /// Perform the local version of the operation (if applicable). /// </summary> LocalOp = 0x200, /// <summary> /// Check that the key for the operation should not be present. /// </summary> CheckNoKey = 0x400, /// <summary> /// Use the sub-region for performing the operation. /// </summary> UseSubRegion = 0x800, /// <summary> /// Do not try to create the sub-region. /// </summary> NoCreateSubRegion = 0x1000, /// <summary> /// Do not re-connect using new credentials rather use the previous /// connection. /// </summary> UseOldConn = 0x2000, } /// <summary> /// This class encapsulates an <see cref="OperationCode"/> with associated flags, the /// client to perform the operation, and the number of operations to perform. /// </summary> public class OperationWithAction { /// <summary> /// The operation to be performed. /// </summary> private OperationCode m_opCode; /// <summary> /// The operation for which authorized or unauthorized credentials have to be /// generated. This is the same as {@link #opCode} when not specified. /// </summary> private OperationCode m_authzOpCode; /// <summary> /// The client number on which the operation has to be performed. /// </summary> private int m_clientNum; /// <summary> /// Bitwise or'd <see cref="OpFlags"/> to change/specify the behaviour of /// the operations. /// </summary> private OpFlags m_flags; /// <summary> /// Indices of the keys array to be used for operations. The keys used /// will be concatenation of <c>KeyPrefix</c> and <c>index</c> integer. /// </summary> private int[] m_indices; /// <summary> /// An index for the operation used for logging. /// </summary> private int m_opNum; /// <summary> /// Indicates end of an operation block which can be used for testing with /// failover. /// </summary> public static readonly OperationWithAction OpBlockEnd = new OperationWithAction( OperationCode.Get, 4); /// <summary> /// Indicates end of an operation block which should not be used for testing /// with failover. /// </summary> public static readonly OperationWithAction OpBlockNoFailover = new OperationWithAction(OperationCode.Get, 5); private void SetIndices(int numOps) { this.m_indices = new int[numOps]; for (int index = 0; index < numOps; ++index) { this.m_indices[index] = index; } } public OperationWithAction(OperationCode opCode) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = 1; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = OpFlags.None; SetIndices(4); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode deniedOpCode, int clientNum, OpFlags flags, int numOps) { this.m_opCode = opCode; this.m_authzOpCode = deniedOpCode; this.m_clientNum = clientNum; this.m_flags = flags; SetIndices(numOps); this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = opCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationWithAction(OperationCode opCode, OperationCode authzOpCode, int clientNum, OpFlags flags, int[] indices) { this.m_opCode = opCode; this.m_authzOpCode = authzOpCode; this.m_clientNum = clientNum; this.m_flags = flags; this.m_indices = indices; this.m_opNum = 0; } public OperationCode OpCode { get { return this.m_opCode; } } public OperationCode AuthzOperationCode { get { return this.m_authzOpCode; } } public int ClientNum { get { return this.m_clientNum; } } public OpFlags Flags { get { return this.m_flags; } } public int[] Indices { get { return this.m_indices; } } public int OpNum { get { return this.m_opNum; } set { this.m_opNum = value; } } public override string ToString() { return "opCode:" + this.m_opCode + ",authOpCode:" + this.m_authzOpCode + ",clientNum:" + this.m_clientNum + ",flags:" + this.m_flags + ",numOps:" + this.m_indices.Length + ",indices:" + IndicesToString(this.m_indices); } } /// <summary> /// Simple interface to generate credentials with authorization based on key /// indices also. This is utilized by the post-operation authorization tests /// <c>ThinClientAuthzObjectModTests</c> where authorization depends on /// the actual keys being used for the operation. /// </summary> public interface TestCredentialGenerator { /// <summary> /// Get allowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get disallowed credentials for the given set of operations in the given /// regions and indices of keys. /// </summary> Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num); /// <summary> /// Get the <see cref="CredentialGenerator"/> if any. /// </summary> /// <returns></returns> CredentialGenerator GetCredentialGenerator(); } /// <summary> /// Contains a <c>AuthzCredentialGenerator</c> and implements the /// <c>TestCredentialGenerator</c> interface. /// </summary> protected class TestAuthzCredentialGenerator : TestCredentialGenerator { private AuthzCredentialGenerator authzGen; public TestAuthzCredentialGenerator(AuthzCredentialGenerator authzGen) { this.authzGen = authzGen; } public Properties<string, string> GetAllowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetAllowedCredentials(opCodes, regionNames, num); } public Properties<string, string> GetDisallowedCredentials(OperationCode[] opCodes, string[] regionNames, int[] keyIndices, int num) { return this.authzGen.GetDisallowedCredentials(opCodes, regionNames, num); } public CredentialGenerator GetCredentialGenerator() { return authzGen.GetCredentialGenerator(); } } } }
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace GLib { using System; using System.Runtime.InteropServices; #region Autogenerated code public class AppInfoAdapter : GLib.GInterfaceAdapter, GLib.AppInfo { public AppInfoAdapter (IntPtr handle) { this.handle = handle; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_type(); private static GLib.GType _gtype = new GLib.GType (g_app_info_get_type ()); public override GLib.GType GType { get { return _gtype; } } IntPtr handle; public override IntPtr Handle { get { return handle; } } public static AppInfo GetObject (IntPtr handle, bool owned) { GLib.Object obj = GLib.Object.GetObject (handle, owned); return GetObject (obj); } public static AppInfo GetObject (GLib.Object obj) { if (obj == null) return null; else if (obj as AppInfo == null) return new AppInfoAdapter (obj.Handle); else return obj as AppInfo; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_executable(IntPtr raw); public string Executable { get { IntPtr raw_ret = g_app_info_get_executable(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_name(IntPtr raw); public string Name { get { IntPtr raw_ret = g_app_info_get_name(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_dup(IntPtr raw); public GLib.AppInfo Dup() { IntPtr raw_ret = g_app_info_dup(Handle); GLib.AppInfo ret = GLib.AppInfoAdapter.GetObject (raw_ret, false); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_equal(IntPtr raw, IntPtr appinfo2); public bool Equal(GLib.AppInfo appinfo2) { bool raw_ret = g_app_info_equal(Handle, appinfo2 == null ? IntPtr.Zero : appinfo2.Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern void g_app_info_reset_type_associations(IntPtr content_type); public static void ResetTypeAssociations(string content_type) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); g_app_info_reset_type_associations(native_content_type); GLib.Marshaller.Free (native_content_type); } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_set_as_default_for_type(IntPtr raw, IntPtr content_type, out IntPtr error); public bool SetAsDefaultForType(string content_type) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_set_as_default_for_type(Handle, native_content_type, out error); bool ret = raw_ret; GLib.Marshaller.Free (native_content_type); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_description(IntPtr raw); public string Description { get { IntPtr raw_ret = g_app_info_get_description(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_create_from_commandline(IntPtr commandline, IntPtr application_name, int flags, out IntPtr error); public static GLib.AppInfo CreateFromCommandline(string commandline, string application_name, GLib.AppInfoCreateFlags flags) { IntPtr native_commandline = GLib.Marshaller.StringToPtrGStrdup (commandline); IntPtr native_application_name = GLib.Marshaller.StringToPtrGStrdup (application_name); IntPtr error = IntPtr.Zero; IntPtr raw_ret = g_app_info_create_from_commandline(native_commandline, native_application_name, (int) flags, out error); GLib.AppInfo ret = GLib.AppInfoAdapter.GetObject (raw_ret, false); GLib.Marshaller.Free (native_commandline); GLib.Marshaller.Free (native_application_name); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_set_as_default_for_extension(IntPtr raw, IntPtr extension, out IntPtr error); public bool SetAsDefaultForExtension(string extension) { IntPtr native_extension = GLib.Marshaller.StringToPtrGStrdup (extension); IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_set_as_default_for_extension(Handle, native_extension, out error); bool ret = raw_ret; GLib.Marshaller.Free (native_extension); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_remove_supports_type(IntPtr raw, IntPtr content_type, out IntPtr error); public bool RemoveSupportsType(string content_type) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_remove_supports_type(Handle, native_content_type, out error); bool ret = raw_ret; GLib.Marshaller.Free (native_content_type); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_launch_uris(IntPtr raw, IntPtr uris, IntPtr launch_context, out IntPtr error); public bool LaunchUris(GLib.List uris, GLib.AppLaunchContext launch_context) { IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_launch_uris(Handle, uris == null ? IntPtr.Zero : uris.Handle, launch_context == null ? IntPtr.Zero : launch_context.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_launch(IntPtr raw, IntPtr files, IntPtr launch_context, out IntPtr error); public bool Launch(GLib.List files, GLib.AppLaunchContext launch_context) { IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_launch(Handle, files == null ? IntPtr.Zero : files.Handle, launch_context == null ? IntPtr.Zero : launch_context.Handle, out error); bool ret = raw_ret; if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_launch_default_for_uri(IntPtr uri, IntPtr launch_context, out IntPtr error); public static bool LaunchDefaultForUri(string uri, GLib.AppLaunchContext launch_context) { IntPtr native_uri = GLib.Marshaller.StringToPtrGStrdup (uri); IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_launch_default_for_uri(native_uri, launch_context == null ? IntPtr.Zero : launch_context.Handle, out error); bool ret = raw_ret; GLib.Marshaller.Free (native_uri); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_commandline(IntPtr raw); public string Commandline { get { IntPtr raw_ret = g_app_info_get_commandline(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_delete(IntPtr raw); public bool Delete() { bool raw_ret = g_app_info_delete(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_id(IntPtr raw); public string Id { get { IntPtr raw_ret = g_app_info_get_id(Handle); string ret = GLib.Marshaller.Utf8PtrToString (raw_ret); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_icon(IntPtr raw); public GLib.Icon Icon { get { IntPtr raw_ret = g_app_info_get_icon(Handle); GLib.Icon ret = GLib.IconAdapter.GetObject (raw_ret, false); return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_can_delete(IntPtr raw); public bool CanDelete() { bool raw_ret = g_app_info_can_delete(Handle); bool ret = raw_ret; return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_should_show(IntPtr raw); public bool ShouldShow { get { bool raw_ret = g_app_info_should_show(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_can_remove_supports_type(IntPtr raw); public bool CanRemoveSupportsType { get { bool raw_ret = g_app_info_can_remove_supports_type(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_add_supports_type(IntPtr raw, IntPtr content_type, out IntPtr error); public bool AddSupportsType(string content_type) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); IntPtr error = IntPtr.Zero; bool raw_ret = g_app_info_add_supports_type(Handle, native_content_type, out error); bool ret = raw_ret; GLib.Marshaller.Free (native_content_type); if (error != IntPtr.Zero) throw new GLib.GException (error); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_supports_uris(IntPtr raw); public bool SupportsUris { get { bool raw_ret = g_app_info_supports_uris(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_default_for_uri_scheme(IntPtr uri_scheme); public static GLib.AppInfo GetDefaultForUriScheme(string uri_scheme) { IntPtr native_uri_scheme = GLib.Marshaller.StringToPtrGStrdup (uri_scheme); IntPtr raw_ret = g_app_info_get_default_for_uri_scheme(native_uri_scheme); GLib.AppInfo ret = GLib.AppInfoAdapter.GetObject (raw_ret, false); GLib.Marshaller.Free (native_uri_scheme); return ret; } [DllImport("libgio-2.0-0.dll")] static extern bool g_app_info_supports_files(IntPtr raw); public bool SupportsFiles { get { bool raw_ret = g_app_info_supports_files(Handle); bool ret = raw_ret; return ret; } } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_default_for_type(IntPtr content_type, bool must_support_uris); public static GLib.AppInfo GetDefaultForType(string content_type, bool must_support_uris) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); IntPtr raw_ret = g_app_info_get_default_for_type(native_content_type, must_support_uris); GLib.AppInfo ret = GLib.AppInfoAdapter.GetObject (raw_ret, false); GLib.Marshaller.Free (native_content_type); return ret; } [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_all_for_type(IntPtr content_type); public static GLib.AppInfo[] GetAllForType(string content_type) { IntPtr native_content_type = GLib.Marshaller.StringToPtrGStrdup (content_type); IntPtr raw_ret = g_app_info_get_all_for_type(native_content_type); GLib.AppInfo[] ret = (GLib.AppInfo[]) GLib.Marshaller.ListPtrToArray (raw_ret, typeof(GLib.List), true, false, typeof(GLib.AppInfo)); GLib.Marshaller.Free (native_content_type); return ret; } #endregion #region Customized extensions #line 1 "AppInfoAdapter.custom" // // AppInfoAdapter.custom // // Author: // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // [DllImport("libgio-2.0-0.dll")] static extern IntPtr g_app_info_get_all(); public static GLib.AppInfo[] GetAll() { IntPtr raw_ret = g_app_info_get_all(); GLib.AppInfo[] ret = (GLib.AppInfo[]) GLib.Marshaller.ListPtrToArray (raw_ret, typeof(GLib.List), true, false, typeof(GLib.AppInfo)); return ret; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Threading; namespace Hydra.Framework.Serialisation { /// <summary> /// Binary Decoder /// </summary> public class BDecode : IDisposable { #region Member Variables private readonly Stream ioStream; private readonly Queue<object> outputCollection = new Queue<object>(); private readonly Thread currentThread; private readonly ManualResetEvent eventReset = new ManualResetEvent(false); private readonly Semaphore semephoreSet = new Semaphore(0, int.MaxValue); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BDecode"/> class. /// </summary> /// <param name="stream">The stream.</param> public BDecode(Stream stream) { ioStream = stream; currentThread = new Thread(DecoderThread); currentThread.IsBackground = true; currentThread.Start(); } #endregion #region Properties /// <summary> /// Gets a value indicating whether this <see cref="BDecode"/> is killed. /// </summary> /// <value><c>true</c> if killed; otherwise, <c>false</c>.</value> private bool Killed { get { return eventReset.WaitOne(0, false); } } #endregion #region Public Methods /// <summary> /// Reads the specified timeout. /// </summary> /// <param name="timeout">The timeout.</param> /// <returns></returns> public object Read(TimeSpan timeout) { if (semephoreSet.WaitOne(timeout, true)) { lock (outputCollection) { return outputCollection.Dequeue(); } } return null; } /// <summary> /// Performs application-defined taskQueue associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { eventReset.Set(); currentThread.Join(TimeSpan.FromSeconds(10)); } #endregion #region Private Methods /// <summary> /// Decoders the thread. /// </summary> private void DecoderThread() { try { while (!Killed) { object obj = ReadObject(); if (obj != null) { lock (outputCollection) outputCollection.Enqueue(obj); semephoreSet.Release(); } } Debug.WriteLine("Exiting Decoder Thread"); } catch (Exception ex) { Debug.WriteLine("Decoder Thread Threw an Exception: " + ex.Message); } } /// <summary> /// Reads the object. /// </summary> /// <returns></returns> private object ReadObject() { int i = ioStream.ReadByte(); if (i == -1) { eventReset.Set(); return null; } char b = (char)i; switch (b) { case 'e': return null; case 'o': return ReadTypedObject(); case 'i': return ReadLong(); case 'l': return ReadList(); case 'd': return ReadDictionary(); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // TODO overflow possible string number = "" + b; while (IsDigit((b = (char)ioStream.ReadByte()))) number += b; int length; int.TryParse(number, out length); byte[] data = new byte[length]; ioStream.Read(data, 0, length); return data; default: throw new ApplicationException("Wow, something bogus in the stream"); } } /// <summary> /// Determines whether the specified c is digit. /// </summary> /// <param name="c">The c.</param> /// <returns> /// <c>true</c> if the specified c is digit; otherwise, <c>false</c>. /// </returns> private static bool IsDigit(char c) { switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; default: return false; } } /// <summary> /// Reads the typed object. /// </summary> /// <returns></returns> private object ReadTypedObject() { string typeName = ReadString(); Dictionary<object, object> fields = ReadObject() as Dictionary<object, object>; ioStream.ReadByte(); // get rid of the 'e' Type t = Type.GetType(typeName); object o = FormatterServices.GetSafeUninitializedObject(t); MemberInfo[] memberInfo = FormatterServices.GetSerializableMembers(t); object[] values = new object[memberInfo.Length]; Dictionary<object, object>.ValueCollection.Enumerator fieldValues = fields.Values.GetEnumerator(); for (int index = 0; index < memberInfo.Length; index++) { fieldValues.MoveNext(); if (memberInfo[index].MemberType == MemberTypes.Field) { FieldInfo fieldInfo = (FieldInfo)memberInfo[index]; TypeConverter tc = TypeDescriptor.GetConverter(fieldInfo.FieldType); if (tc.CanConvertFrom(fieldValues.Current.GetType())) values[index] = tc.ConvertFrom(fieldValues.Current); else { TypeConverter tcv = TypeDescriptor.GetConverter(fieldValues.Current.GetType()); object value = tcv.ConvertTo(fieldValues.Current, typeof(string)); values[index] = tc.ConvertFrom(value); } } } FormatterServices.PopulateObjectMembers(o, memberInfo, values); return o; } /// <summary> /// Reads the dictionary. /// </summary> /// <returns></returns> private Dictionary<object, object> ReadDictionary() { Dictionary<object, object> dictionary = new Dictionary<object, object>(); object obj; while ((obj = ReadObject()) != null) { string key = Encoding.UTF8.GetString((byte[])obj); object value = ReadObject(); if (value.GetType() == typeof(byte[])) value = Encoding.UTF8.GetString((byte[])value); dictionary.Add(key, value); } return dictionary; } /// <summary> /// Reads the string. /// </summary> /// <returns></returns> private string ReadString() { string s = Encoding.UTF8.GetString(ReadObject() as byte[]); return s; } /// <summary> /// Reads the list. /// </summary> /// <returns></returns> private List<object> ReadList() { List<object> objects = new List<object>(); object obj; while ((obj = ReadObject()) != null) objects.Add(obj); return objects; } /// <summary> /// Reads the long. /// </summary> /// <returns></returns> private long ReadLong() { string number = ""; char b; while ((b = (char)ioStream.ReadByte()) != 'e') number += b; return long.Parse(number); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace osu.Game.IO.Legacy { /// <summary> SerializationReader. Extends BinaryReader to add additional data types, /// handle null strings and simplify use with ISerializable. </summary> public class SerializationReader : BinaryReader { private readonly Stream stream; public SerializationReader(Stream s) : base(s, Encoding.UTF8) { stream = s; } public int RemainingBytes => (int)(stream.Length - stream.Position); /// <summary> Static method to take a SerializationInfo object (an input to an ISerializable constructor) /// and produce a SerializationReader from which serialized objects can be read </summary>. public static SerializationReader GetReader(SerializationInfo info) { byte[] byteArray = (byte[])info.GetValue("X", typeof(byte[])); MemoryStream ms = new MemoryStream(byteArray); return new SerializationReader(ms); } /// <summary> Reads a string from the buffer. Overrides the base implementation so it can cope with nulls. </summary> public override string ReadString() { if (ReadByte() == 0) return null; return base.ReadString(); } /// <summary> Reads a byte array from the buffer, handling nulls and the array length. </summary> public byte[] ReadByteArray() { int len = ReadInt32(); if (len > 0) return ReadBytes(len); if (len < 0) return null; return Array.Empty<byte>(); } /// <summary> Reads a char array from the buffer, handling nulls and the array length. </summary> public char[] ReadCharArray() { int len = ReadInt32(); if (len > 0) return ReadChars(len); if (len < 0) return null; return Array.Empty<char>(); } /// <summary> Reads a DateTime from the buffer. </summary> public DateTime ReadDateTime() { long ticks = ReadInt64(); if (ticks < 0) throw new IOException("Bad ticks count read!"); return new DateTime(ticks, DateTimeKind.Utc); } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadBList<T>(bool skipErrors = false) where T : ILegacySerializable, new() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); SerializationReader sr = new SerializationReader(BaseStream); for (int i = 0; i < count; i++) { T obj = new T(); try { obj.ReadFromStream(sr); } catch (Exception) { if (skipErrors) continue; throw; } d.Add(obj); } return d; } /// <summary> Reads a generic list from the buffer. </summary> public IList<T> ReadList<T>() { int count = ReadInt32(); if (count < 0) return null; IList<T> d = new List<T>(count); for (int i = 0; i < count; i++) d.Add((T)ReadObject()); return d; } /// <summary> Reads a generic Dictionary from the buffer. </summary> public IDictionary<TKey, TValue> ReadDictionary<TKey, TValue>() { int count = ReadInt32(); if (count < 0) return null; IDictionary<TKey, TValue> d = new Dictionary<TKey, TValue>(); for (int i = 0; i < count; i++) d[(TKey)ReadObject()] = (TValue)ReadObject(); return d; } /// <summary> Reads an object which was added to the buffer by WriteObject. </summary> public object ReadObject() { ObjType t = (ObjType)ReadByte(); switch (t) { case ObjType.boolType: return ReadBoolean(); case ObjType.byteType: return ReadByte(); case ObjType.uint16Type: return ReadUInt16(); case ObjType.uint32Type: return ReadUInt32(); case ObjType.uint64Type: return ReadUInt64(); case ObjType.sbyteType: return ReadSByte(); case ObjType.int16Type: return ReadInt16(); case ObjType.int32Type: return ReadInt32(); case ObjType.int64Type: return ReadInt64(); case ObjType.charType: return ReadChar(); case ObjType.stringType: return base.ReadString(); case ObjType.singleType: return ReadSingle(); case ObjType.doubleType: return ReadDouble(); case ObjType.decimalType: return ReadDecimal(); case ObjType.dateTimeType: return ReadDateTime(); case ObjType.byteArrayType: return ReadByteArray(); case ObjType.charArrayType: return ReadCharArray(); case ObjType.otherType: return DynamicDeserializer.Deserialize(BaseStream); default: return null; } } public static class DynamicDeserializer { private static VersionConfigToNamespaceAssemblyObjectBinder versionBinder; private static BinaryFormatter formatter; private static void initialize() { versionBinder = new VersionConfigToNamespaceAssemblyObjectBinder(); formatter = new BinaryFormatter { // AssemblyFormat = FormatterAssemblyStyle.Simple, Binder = versionBinder }; } public static object Deserialize(Stream stream) { if (formatter == null) initialize(); Debug.Assert(formatter != null, "formatter != null"); // ReSharper disable once PossibleNullReferenceException return formatter.Deserialize(stream); } #region Nested type: VersionConfigToNamespaceAssemblyObjectBinder public sealed class VersionConfigToNamespaceAssemblyObjectBinder : SerializationBinder { private readonly Dictionary<string, Type> cache = new Dictionary<string, Type>(); public override Type BindToType(string assemblyName, string typeName) { if (cache.TryGetValue(assemblyName + typeName, out var typeToDeserialize)) return typeToDeserialize; List<Type> tmpTypes = new List<Type>(); Type genType = null; if (typeName.Contains("System.Collections.Generic") && typeName.Contains("[[")) { string[] splitTyps = typeName.Split('['); foreach (string typ in splitTyps) { if (typ.Contains("Version")) { string asmTmp = typ.Substring(typ.IndexOf(',') + 1); string asmName = asmTmp.Remove(asmTmp.IndexOf(']')).Trim(); string typName = typ.Remove(typ.IndexOf(',')); tmpTypes.Add(BindToType(asmName, typName)); } else if (typ.Contains("Generic")) { genType = BindToType(assemblyName, typ); } } if (genType != null && tmpTypes.Count > 0) { return genType.MakeGenericType(tmpTypes.ToArray()); } } string toAssemblyName = assemblyName.Split(',')[0]; Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly a in assemblies) { if (a.FullName.Split(',')[0] == toAssemblyName) { typeToDeserialize = a.GetType(typeName); break; } } cache.Add(assemblyName + typeName, typeToDeserialize); return typeToDeserialize; } } #endregion } } public enum ObjType : byte { nullType, boolType, byteType, uint16Type, uint32Type, uint64Type, sbyteType, int16Type, int32Type, int64Type, charType, stringType, singleType, doubleType, decimalType, dateTimeType, byteArrayType, charArrayType, otherType, ILegacySerializableType } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Tacto.Core { public class Person { public const string WebProtocolPrefix = "http://"; public enum Format { CSV, HTML, VCF }; public ReadOnlyCollection<string> TrimAddressPrefixes = new ReadOnlyCollection<string>( new string[] { "c\\", "c/", "avenida", "avda." } ); public static readonly ReadOnlyCollection<string> FormatNames = new ReadOnlyCollection<string>( new string[]{ "CSV", "HTML", "VCF" } ); public Person() :this( "Doe", "John", "john@doe.com", "0", null ) { } public Person(string surname, string name, string email, string phone) :this( surname, name, email, phone, null ) { } public Person(string surname, string name, string email, string phone, Category[] categories) { this.Surname = surname; this.Name = name; this.Email = email; this.WorkPhone = phone; this.HomePhone = MobilePhone = ""; this.Address = ""; this.Email2 = ""; this.Id = ""; this.Comments = ""; this.Web = ""; if ( categories != null ) { this.Categories = categories; } if ( !this.IsEnoughData() ) { throw new ApplicationException( "Person built without enough data" ); } } public string Address { get { return this.address; } set { this.address = value.Trim(); foreach(string prefix in TrimAddressPrefixes) { if ( this.address.ToLower().StartsWith( prefix ) ) { this.address = this.address.Substring( prefix.Length ).TrimStart(); } } } } public string Email2 { get { return this.email2; } set { this.email2 = FormatEmail( value ); } } public string Name { get { return name; } set { name = NormalizeText( value ); } } public string Surname { get { return this.surname; } set { this.surname = NormalizeText( value ); } } public string AnyEmail { get { if ( this.Email.Length == 0 ) return this.Email2; else return this.Email; } } public Tacto.Core.Category[] Categories { get { return this.categories.ToArray(); } set { this.AppendCategories( value ); } } protected void AppendCategories(Category[] categories) { // Eliminate possible spurious categories List<Category> l = new List<Category>( categories ); l.RemoveAll( x => x == null ); this.categories.AppendRange( l.ToArray() ); } /// <summary> /// Gets or sets the identifier. /// This can be a DNI or Passport number. /// </summary> /// <value>The identifier.</value> public string Id { get { return id; } set { this.id = value.Trim().ToUpper(); } } public string Comments { get { return comments; } set { this.comments = value.Trim(); } } public string Email { get { return this.email; } set { this.email = FormatEmail( value ); } } public string Web { get { return this.web; } set { this.web = FormatWeb( value ); } } public string MobilePhone { get { return this.mobilePhone; } set { this.mobilePhone = FormatPhoneNumber( value ); } } public string HomePhone { get { return this.homePhone; } set { this.homePhone = FormatPhoneNumber( value ); } } public string WorkPhone { get { return this.workPhone; } set { this.workPhone = FormatPhoneNumber( value ); } } public string AnyPhone { get { if ( this.MobilePhone.Length == 0 ) { if ( this.HomePhone.Length == 0 ) { return this.WorkPhone; } else { return this.HomePhone; } } else { return MobilePhone; } } } /// <summary> /// Clone this instance. /// </summary> public Person Clone() { var toret = new Person(); toret.Id = this.Id; toret.Comments = this.Comments; toret.Surname = this.Surname; toret.Name = this.Name; toret.Email = this.Email; toret.Email2 = this.Email2; toret.Web = this.Web; toret.WorkPhone = this.WorkPhone; toret.HomePhone = this.HomePhone; toret.MobilePhone = this.MobilePhone; toret.Categories = this.Categories; toret.Address = this.Address; return toret; } /// <summary> /// Determines whether this instance has enough data. /// </summary> /// <returns><c>true</c> if this instance has enough data; otherwise, <c>false</c>.</returns> public bool IsEnoughData() { return ( this.Surname.Length > 0 && this.Name.Length > 0 && this.AnyEmail.Length > 0 && this.AnyPhone.Length > 0 ); } /// <summary> /// Determines whether this instance has the specified category. /// </summary> /// <returns><c>true</c> if this instance has the specified category; otherwise, <c>false</c>.</returns> /// <param name="category">The category, as a Category object.</param> public bool HasCategory(Category category) { return ( this.categories.LookFor( category.Name ) != null ); } /// <summary> /// Removes a given category. /// </summary> /// <param name="category">The category to remove, as a Category object.</param> public void RemoveCategory(Category category) { if ( category == null || category.Name.Trim().Length == 0 ) { throw new ApplicationException( "internal: invalid category name" ); } RemoveCategory( category.Name ); } /// <summary> /// Removes a given category. /// </summary> /// <param name="categoryText">A category, as string.</param> public void RemoveCategory(string categoryText) { int i = 0; categoryText = Category.Encode( categoryText ); int numCategories = categories.Size(); for(; i < numCategories; ++i) { if ( Category.Encode( categories.Get( i ).Name ) == categoryText ) { categories.Remove( i ); break; } } if ( i >= numCategories ) { throw new ApplicationException( "category '" + categoryText + "' does not exist" ); } return; } /// <summary> /// Returns a brief summary <see cref="System.String"/> that represents the current <see cref="Tacto.Core.Person"/>. /// </summary> /// <returns>A brief summary <see cref="System.String"/> that represents the current <see cref="Tacto.Core.Person"/>.</returns> public override string ToString() { return ( Surname + ", " + Name + "(" + Email + "): " + WorkPhone ); } /// <summary> /// Converts the Person info to CSV, assuming comma as delimiter. /// @see CsvManager.CommaDelimiter /// </summary> /// <returns>The resulting info in csv format, as string.</returns> public string ToCsv() { return ToCsv( CsvManager.CommaDelimiter ); } /// <summary> /// Converts the Person info to CSV /// </summary> /// <returns>The resulting info in csv format, as string.</returns> /// <param name="delimiter">The delimiter, normally "," or ";".</param> public string ToCsv(char delimiter) { return ( '\"' + this.Surname + '\"' + delimiter + '\"' + this.Name + '\"' + delimiter + '\"' + this.Address + '\"' + delimiter + '\"' + this.Email + '\"' + delimiter + '\"' + this.Email2 + '\"' + delimiter + '\"' + this.Web + '\"' + delimiter + '\"' + this.WorkPhone + '\"' + delimiter + '\"' + this.HomePhone + '\"' + delimiter + '\"' + this.MobilePhone + '\"' + delimiter + '\"' + this.Id + '\"' + delimiter + '\"' + this.Comments + '\"' ); } /// <summary> /// Converts the info of this Person to HTML. /// </summary> /// <returns>The resulting HTML, as a string.</returns> public string ToHtml() { return ( "<tr>" + "<td>" + Surname + "</td>" + "<td>" + Name + "</td>" + "<td>" + Address + "</td>" + "<td>" + Email + "</td>" + "<td>" + Email2 + "</td>" + "<td>" + Web + "</td>" + "<td>" + WorkPhone + "</td>" + "<td>" + HomePhone + "</td>" + "<td>" + MobilePhone + "</td>" + "<td>" + Id + "</td>" + "<td>" + Comments + "</td>" + "</tr>" ); } /// <summary> /// Cnvts any text for suitability to VCard. /// </summary> /// <returns>The text converted, as string.</returns> /// <param name="field">The text to convert.</param> public static string CnvtForSuitabilityToVCard(string field) { return field.Replace( ";", "\\;" ).Replace( ",", "\\," ).Replace( "\\", "\\\\" ); } /// <summary> /// Converts the info of this Person to a VCard /// </summary> /// <returns>The VCard, as a string.</returns> public string ToVCard() { string escName = CnvtForSuitabilityToVCard( this.Name ); string escSurame = CnvtForSuitabilityToVCard( this.Surname ); string escAddress = CnvtForSuitabilityToVCard( this.Address ); string escWorkPhone = CnvtForSuitabilityToVCard( this.WorkPhone ); string escMobilePhone = CnvtForSuitabilityToVCard( this.MobilePhone ); string escHomePhone = CnvtForSuitabilityToVCard( this.HomePhone ); string escEmail = CnvtForSuitabilityToVCard( this.Email ); string escEmail2 = CnvtForSuitabilityToVCard( this.Email2 ); string escWeb = CnvtForSuitabilityToVCard( this.Web ); return ( "BEGIN:VCARD\nVERSION:3.0\n" + "N;CHARSET=UTF-8:" + escSurame + ";" + escName + "\n" + "FN;CHARSET=UTF-8:" + escName + " " + escSurame + "\n" + "ADR;TYPE=HOME;CHARSET=UTF-8:" + escAddress + "\n" + "TEL;TYPE=WORK,VOICE;CHARSET=UTF-8:" + escWorkPhone + "\n" + "TEL;TYPE=HOME,VOICE;CHARSET=UTF-8:" + escHomePhone + "\n" + "TEL;TYPE=MOBILE,VOICE, MSG;CHARSET=UTF-8:" + escMobilePhone + "\n" + "EMAIL;TYPE=PREF,INTERNET;CHARSET=UTF-8:" + escEmail + "\n" + "EMAIL;TYPE=INTERNET;CHARSET=UTF-8:" + escEmail2 + "\n" + "URL:" + escWeb + "\n" + "END:VCARD\n" ); } /// <summary> /// Looks for something in this Person record. /// </summary> /// <returns><c>true</c>, if it was found, <c>false</c> otherwise.</returns> /// <param name="txt">A text to look for.</param> public bool LookFor(string txt) { return this.Name.ToLower().Contains( txt ) || this.Surname.ToLower().Contains( txt ) || this.Address.ToLower().Contains( txt ) || this.Email.ToLower().Contains( txt ) || this.Email2.ToLower().Contains( txt ) || this.Web.ToLower().Contains( txt ) || this.WorkPhone.ToLower().Contains( txt ) || this.MobilePhone.ToLower().Contains( txt ) || this.HomePhone.ToLower().Contains( txt ) || this.Id.ToLower().Contains( txt ) || this.Comments.ToLower().Contains( txt ) ; } public void Convert(Format format, string fileName) { System.IO.StreamWriter file = new System.IO.StreamWriter( fileName ); if ( format == Format.CSV ) { file.WriteLine( this.ToCsv() ); } else if ( format == Format.HTML ) { file.WriteLine( this.ToHtml() ); } else if ( format == Format.VCF ) { file.WriteLine( this.ToVCard() ); } file.Close(); return; } /// <summary> /// Formats a phone number. /// </summary> /// <returns>The new, formatted, phone number, as string.</returns> /// <param name="txtPhone">The phone, as a string.</param> public static string FormatPhoneNumber(string txtPhone) { txtPhone = txtPhone.Trim(); var aux = ""; var toret = ""; // Remove all text without digits foreach (char ch in txtPhone) { if( ch == '+' || char.IsDigit( ch ) ) { aux += ch; } } // Group them by three, starting from the right while ( aux.Length > 2 ) { toret = aux.Substring( aux.Length - 3, 3 ) + ' ' + toret; aux = aux.Remove( aux.Length - 3 ); } // Add the remaining parts if ( aux.Length > 0 ) { toret = aux + ' ' + toret; } return toret.Trim(); } /// <summary> /// Formats the email. /// </summary> /// <returns>The new, formatted, email, as a string.</returns> /// <param name="txtEmail">The email, as string.</param> public static string FormatEmail(string txtEmail) { return txtEmail.Trim().ToLower(); } /// <summary> /// Formats the web. /// </summary> /// <returns>The new, formatted, web, as a string.</returns> /// <param name="txtEmail">The web, as string.</param> public static string FormatWeb(string txtWeb) { txtWeb = txtWeb.Trim().ToLower(); if ( !txtWeb.StartsWith( WebProtocolPrefix ) ) { txtWeb = WebProtocolPrefix + txtWeb; } return txtWeb; } /// <summary> /// Normalizes any text. /// Normalized text has all chars in lowercase, except /// the first letter of each word. /// </summary> /// <returns>The normalized text, as string.</returns> /// <param name="txt">Text.</param> public static string NormalizeText(string txt) { txt = txt.Trim().ToLower(); if ( txt.Length > 0 ) { txt = char.ToUpper( txt[ 0 ] ) + txt.Substring( 1 ); for(int pos = 0; pos < txt.Length; ++pos) { if ( txt[ pos ] == ' ' || txt[ pos ] == '-' ) { if ( ( pos - 2 ) < txt.Length ) { txt = txt.Substring( 0, pos + 1 ) + char.ToUpper( txt[ pos + 1 ] ) + txt.Substring( pos + 2 ); ++pos; } } } } return txt; } private string name; private string surname; private string address; private string email; private string email2; private string workPhone; private string homePhone; private string mobilePhone; private string id; private string comments; private string web; private CategoryList categories = new CategoryList(); } }
// 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 utilizes partial class feature and contains // only internal implementation of UriParser type using System.Collections.Generic; using System.Diagnostics; namespace System { // This enum specifies the Uri syntax flags that is understood by builtin Uri parser. [Flags] internal enum UriSyntaxFlags { None = 0x0, MustHaveAuthority = 0x1, // must have "//" after scheme: OptionalAuthority = 0x2, // used by generic parser due to unknown Uri syntax MayHaveUserInfo = 0x4, MayHavePort = 0x8, MayHavePath = 0x10, MayHaveQuery = 0x20, MayHaveFragment = 0x40, AllowEmptyHost = 0x80, AllowUncHost = 0x100, AllowDnsHost = 0x200, AllowIPv4Host = 0x400, AllowIPv6Host = 0x800, AllowAnInternetHost = AllowDnsHost | AllowIPv4Host | AllowIPv6Host, AllowAnyOtherHost = 0x1000, // Relaxed authority syntax FileLikeUri = 0x2000, //Special case to allow file:\\balbla or file://\\balbla MailToLikeUri = 0x4000, //V1 parser inheritance mailTo:AuthorityButNoSlashes V1_UnknownUri = 0x10000, // a Compatibility with V1 parser for an unknown scheme SimpleUserSyntax = 0x20000, // It is safe to not call virtual UriParser methods BuiltInSyntax = 0x40000, // This is a simple Uri plus it is hardcoded in the product ParserSchemeOnly = 0x80000, // This is a Parser that does only Uri scheme parsing AllowDOSPath = 0x100000, // will check for "x:\" PathIsRooted = 0x200000, // For an authority based Uri the first path char is '/' ConvertPathSlashes = 0x400000, // will turn '\' into '/' CompressPath = 0x800000, // For an authority based Uri remove/compress /./ /../ in the path CanonicalizeAsFilePath = 0x1000000, // remove/convert sequences /.../ /x../ /x./ dangerous for a DOS path UnEscapeDotsAndSlashes = 0x2000000, // additionally unescape dots and slashes before doing path compression AllowIdn = 0x4000000, // IDN host conversion allowed AllowIriParsing = 0x10000000, // Iri parsing. String is normalized, bidi control // characters are removed, unicode char limits are checked etc. // KeepTailLWS = 0x8000000, } // // Only internal members are included here // public abstract partial class UriParser { private static readonly LowLevelDictionary<string, UriParser> s_table; private static LowLevelDictionary<string, UriParser> s_tempTable; private UriSyntaxFlags _flags; // Some flags (specified in c_UpdatableFlags) besides being set in the ctor, can also be set at a later // point. Such "updatable" flags can be set using SetUpdatableFlags(); if this method is called, // the value specified in the ctor is ignored (i.e. for all c_UpdatableFlags the value in m_Flags is // ignored), and the new value is used (i.e. for all c_UpdatableFlags the value in m_UpdatableFlags is used). private volatile UriSyntaxFlags _updatableFlags; private volatile bool _updatableFlagsUsed; // The following flags can be updated at any time. private const UriSyntaxFlags c_UpdatableFlags = UriSyntaxFlags.UnEscapeDotsAndSlashes; private int _port; private string _scheme; internal const int NoDefaultPort = -1; private const int c_InitialTableSize = 25; // These are always available without paying hashtable lookup cost // Note: see UpdateStaticSyntaxReference() internal static UriParser HttpUri; internal static UriParser HttpsUri; internal static UriParser WsUri; internal static UriParser WssUri; internal static UriParser FtpUri; internal static UriParser FileUri; internal static UriParser GopherUri; internal static UriParser NntpUri; internal static UriParser NewsUri; internal static UriParser MailToUri; internal static UriParser UuidUri; internal static UriParser TelnetUri; internal static UriParser LdapUri; internal static UriParser NetTcpUri; internal static UriParser NetPipeUri; internal static UriParser VsMacrosUri; static UriParser() { s_table = new LowLevelDictionary<string, UriParser>(c_InitialTableSize); s_tempTable = new LowLevelDictionary<string, UriParser>(c_InitialTableSize); //Now we will call for the instance constructors that will interrupt this static one. // Below we simulate calls into FetchSyntax() but avoid using lock() and other things redundant for a .cctor HttpUri = new BuiltInUriParser("http", 80, HttpSyntaxFlags); s_table[HttpUri.SchemeName] = HttpUri; //HTTP HttpsUri = new BuiltInUriParser("https", 443, HttpUri._flags); s_table[HttpsUri.SchemeName] = HttpsUri; //HTTPS cloned from HTTP WsUri = new BuiltInUriParser("ws", 80, HttpSyntaxFlags); s_table[WsUri.SchemeName] = WsUri; // WebSockets WssUri = new BuiltInUriParser("wss", 443, HttpSyntaxFlags); s_table[WssUri.SchemeName] = WssUri; // Secure WebSockets FtpUri = new BuiltInUriParser("ftp", 21, FtpSyntaxFlags); s_table[FtpUri.SchemeName] = FtpUri; //FTP FileUri = new BuiltInUriParser("file", NoDefaultPort, s_fileSyntaxFlags); s_table[FileUri.SchemeName] = FileUri; //FILE GopherUri = new BuiltInUriParser("gopher", 70, GopherSyntaxFlags); s_table[GopherUri.SchemeName] = GopherUri; //GOPHER NntpUri = new BuiltInUriParser("nntp", 119, NntpSyntaxFlags); s_table[NntpUri.SchemeName] = NntpUri; //NNTP NewsUri = new BuiltInUriParser("news", NoDefaultPort, NewsSyntaxFlags); s_table[NewsUri.SchemeName] = NewsUri; //NEWS MailToUri = new BuiltInUriParser("mailto", 25, MailtoSyntaxFlags); s_table[MailToUri.SchemeName] = MailToUri; //MAILTO UuidUri = new BuiltInUriParser("uuid", NoDefaultPort, NewsUri._flags); s_table[UuidUri.SchemeName] = UuidUri; //UUID cloned from NEWS TelnetUri = new BuiltInUriParser("telnet", 23, TelnetSyntaxFlags); s_table[TelnetUri.SchemeName] = TelnetUri; //TELNET LdapUri = new BuiltInUriParser("ldap", 389, LdapSyntaxFlags); s_table[LdapUri.SchemeName] = LdapUri; //LDAP NetTcpUri = new BuiltInUriParser("net.tcp", 808, NetTcpSyntaxFlags); s_table[NetTcpUri.SchemeName] = NetTcpUri; NetPipeUri = new BuiltInUriParser("net.pipe", NoDefaultPort, NetPipeSyntaxFlags); s_table[NetPipeUri.SchemeName] = NetPipeUri; VsMacrosUri = new BuiltInUriParser("vsmacros", NoDefaultPort, VsmacrosSyntaxFlags); s_table[VsMacrosUri.SchemeName] = VsMacrosUri; //VSMACROS } private class BuiltInUriParser : UriParser { // // All BuiltIn parsers use that ctor. They are marked with "simple" and "built-in" flags // internal BuiltInUriParser(string lwrCaseScheme, int defaultPort, UriSyntaxFlags syntaxFlags) : base((syntaxFlags | UriSyntaxFlags.SimpleUserSyntax | UriSyntaxFlags.BuiltInSyntax)) { _scheme = lwrCaseScheme; _port = defaultPort; } } internal UriSyntaxFlags Flags { get { return _flags; } } internal bool NotAny(UriSyntaxFlags flags) { // Return true if none of the flags specified in 'flags' are set. return IsFullMatch(flags, UriSyntaxFlags.None); } internal bool InFact(UriSyntaxFlags flags) { // Return true if at least one of the flags in 'flags' is set. return !IsFullMatch(flags, UriSyntaxFlags.None); } internal bool IsAllSet(UriSyntaxFlags flags) { // Return true if all flags in 'flags' are set. return IsFullMatch(flags, flags); } private bool IsFullMatch(UriSyntaxFlags flags, UriSyntaxFlags expected) { // Return true, if masking the current set of flags with 'flags' equals 'expected'. // Definition 'current set of flags': // a) if updatable flags were never set: m_Flags // b) if updatable flags were set: set union between all flags in m_Flags which are not updatable // (i.e. not part of c_UpdatableFlags) and all flags in m_UpdatableFlags UriSyntaxFlags mergedFlags; // if none of the flags in 'flags' is an updatable flag, we ignore m_UpdatableFlags if (((flags & c_UpdatableFlags) == 0) || !_updatableFlagsUsed) { mergedFlags = _flags; } else { // mask m_Flags to only use the flags not in c_UpdatableFlags mergedFlags = (_flags & (~c_UpdatableFlags)) | _updatableFlags; } return (mergedFlags & flags) == expected; } // // Internal .ctor, any ctor eventually goes through this one // internal UriParser(UriSyntaxFlags flags) { _flags = flags; _scheme = string.Empty; } private static void FetchSyntax(UriParser syntax, string lwrCaseSchemeName, int defaultPort) { if (syntax.SchemeName.Length != 0) throw new InvalidOperationException(SR.Format(SR.net_uri_NeedFreshParser, syntax.SchemeName)); lock (s_table) { syntax._flags &= ~UriSyntaxFlags.V1_UnknownUri; UriParser oldSyntax = null; s_table.TryGetValue(lwrCaseSchemeName, out oldSyntax); if (oldSyntax != null) throw new InvalidOperationException(SR.Format(SR.net_uri_AlreadyRegistered, oldSyntax.SchemeName)); s_tempTable.TryGetValue(syntax.SchemeName, out oldSyntax); if (oldSyntax != null) { // optimization on schemeName, will try to keep the first reference lwrCaseSchemeName = oldSyntax._scheme; s_tempTable.Remove(lwrCaseSchemeName); } syntax.OnRegister(lwrCaseSchemeName, defaultPort); syntax._scheme = lwrCaseSchemeName; syntax.CheckSetIsSimpleFlag(); syntax._port = defaultPort; s_table[syntax.SchemeName] = syntax; } } private const int c_MaxCapacity = 512; //schemeStr must be in lower case! internal static UriParser FindOrFetchAsUnknownV1Syntax(string lwrCaseScheme) { // check may be other thread just added one UriParser syntax = null; s_table.TryGetValue(lwrCaseScheme, out syntax); if (syntax != null) { return syntax; } s_tempTable.TryGetValue(lwrCaseScheme, out syntax); if (syntax != null) { return syntax; } lock (s_table) { if (s_tempTable.Count >= c_MaxCapacity) { s_tempTable = new LowLevelDictionary<string, UriParser>(c_InitialTableSize); } syntax = new BuiltInUriParser(lwrCaseScheme, NoDefaultPort, UnknownV1SyntaxFlags); s_tempTable[lwrCaseScheme] = syntax; return syntax; } } internal static UriParser GetSyntax(string lwrCaseScheme) { UriParser ret = null; s_table.TryGetValue(lwrCaseScheme, out ret); if (ret == null) { s_tempTable.TryGetValue(lwrCaseScheme, out ret); } return ret; } // // Builtin and User Simple syntaxes do not need custom validation/parsing (i.e. virtual method calls), // internal bool IsSimple { get { return InFact(UriSyntaxFlags.SimpleUserSyntax); } } internal void CheckSetIsSimpleFlag() { Type type = this.GetType(); if ( type == typeof(GenericUriParser) || type == typeof(HttpStyleUriParser) || type == typeof(FtpStyleUriParser) || type == typeof(FileStyleUriParser) || type == typeof(NewsStyleUriParser) || type == typeof(GopherStyleUriParser) || type == typeof(NetPipeStyleUriParser) || type == typeof(NetTcpStyleUriParser) || type == typeof(LdapStyleUriParser) ) { _flags |= UriSyntaxFlags.SimpleUserSyntax; } } // // This method is used to update flags. The scenario where this is needed is when the user specifies // flags in the config file. The config file is read after UriParser instances were created. // internal void SetUpdatableFlags(UriSyntaxFlags flags) { Debug.Assert(!_updatableFlagsUsed, "SetUpdatableFlags() already called. It can only be called once per parser."); Debug.Assert((flags & (~c_UpdatableFlags)) == 0, "Only updatable flags can be set."); // No locks necessary. Reordering won't happen due to volatile. _updatableFlags = flags; _updatableFlagsUsed = true; } // // These are simple internal wrappers that will call virtual protected methods // (to avoid "protected internal" signatures in the public docs) // internal UriParser InternalOnNewUri() { UriParser effectiveParser = OnNewUri(); if ((object)this != (object)effectiveParser) { effectiveParser._scheme = _scheme; effectiveParser._port = _port; effectiveParser._flags = _flags; } return effectiveParser; } internal void InternalValidate(Uri thisUri, out UriFormatException parsingError) { InitializeAndValidate(thisUri, out parsingError); } internal string InternalResolve(Uri thisBaseUri, Uri uriLink, out UriFormatException parsingError) { return Resolve(thisBaseUri, uriLink, out parsingError); } internal bool InternalIsBaseOf(Uri thisBaseUri, Uri uriLink) { return IsBaseOf(thisBaseUri, uriLink); } internal string InternalGetComponents(Uri thisUri, UriComponents uriComponents, UriFormat uriFormat) { return GetComponents(thisUri, uriComponents, uriFormat); } internal bool InternalIsWellFormedOriginalString(Uri thisUri) { return IsWellFormedOriginalString(thisUri); } // // Various Uri scheme syntax flags // private const UriSyntaxFlags UnknownV1SyntaxFlags = UriSyntaxFlags.V1_UnknownUri | // This flag must be always set here UriSyntaxFlags.OptionalAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveQuery | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowEmptyHost | UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowDOSPath | // V1 compat, actually we should not parse DOS file out of an unknown scheme UriSyntaxFlags.ConvertPathSlashes | // V1 compat, it will always convert backslashes UriSyntaxFlags.CompressPath | // V1 compat, it will always compress path even for non hierarchical Uris UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags HttpSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveQuery | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.PathIsRooted | // UriSyntaxFlags.ConvertPathSlashes | UriSyntaxFlags.CompressPath | UriSyntaxFlags.CanonicalizeAsFilePath | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags FtpSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.PathIsRooted | // UriSyntaxFlags.ConvertPathSlashes | UriSyntaxFlags.CompressPath | UriSyntaxFlags.CanonicalizeAsFilePath | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private static readonly UriSyntaxFlags s_fileSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.AllowEmptyHost | UriSyntaxFlags.AllowUncHost | UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | UriSyntaxFlags.MayHaveQuery | // UriSyntaxFlags.FileLikeUri | // UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowDOSPath | // UriSyntaxFlags.ConvertPathSlashes | UriSyntaxFlags.CompressPath | UriSyntaxFlags.CanonicalizeAsFilePath | UriSyntaxFlags.UnEscapeDotsAndSlashes | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags VsmacrosSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.AllowEmptyHost | UriSyntaxFlags.AllowUncHost | UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.FileLikeUri | // UriSyntaxFlags.AllowDOSPath | UriSyntaxFlags.ConvertPathSlashes | UriSyntaxFlags.CompressPath | UriSyntaxFlags.CanonicalizeAsFilePath | UriSyntaxFlags.UnEscapeDotsAndSlashes | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags GopherSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; // UriSyntaxFlags.KeepTailLWS | //Note that NNTP and NEWS are quite different in syntax private const UriSyntaxFlags NewsSyntaxFlags = UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags NntpSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags TelnetSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags LdapSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | // UriSyntaxFlags.AllowEmptyHost | UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveQuery | UriSyntaxFlags.MayHaveFragment | // UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags MailtoSyntaxFlags = // UriSyntaxFlags.AllowEmptyHost | UriSyntaxFlags.AllowUncHost | // V1 compat UriSyntaxFlags.AllowAnInternetHost | // UriSyntaxFlags.MayHaveUserInfo | UriSyntaxFlags.MayHavePort | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveFragment | UriSyntaxFlags.MayHaveQuery | //to maintain compat // UriSyntaxFlags.MailToLikeUri | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags NetPipeSyntaxFlags = UriSyntaxFlags.MustHaveAuthority | UriSyntaxFlags.MayHavePath | UriSyntaxFlags.MayHaveQuery | UriSyntaxFlags.MayHaveFragment | UriSyntaxFlags.AllowAnInternetHost | UriSyntaxFlags.PathIsRooted | UriSyntaxFlags.ConvertPathSlashes | UriSyntaxFlags.CompressPath | UriSyntaxFlags.CanonicalizeAsFilePath | UriSyntaxFlags.UnEscapeDotsAndSlashes | UriSyntaxFlags.AllowIdn | UriSyntaxFlags.AllowIriParsing; private const UriSyntaxFlags NetTcpSyntaxFlags = NetPipeSyntaxFlags | UriSyntaxFlags.MayHavePort; } }
using System.Collections.Generic; using UnityEngine; using UnityEditor; using UMA.Editors; namespace UMA.CharacterSystem.Editors { [CustomEditor(typeof(DynamicDNAConverterCustomizer), true)] public class DynamicDNAConverterCustomizerEditor : Editor { DynamicDNAConverterCustomizer thisDDCC; Dictionary<IDNAConverter, Editor> SDCBs = new Dictionary<IDNAConverter, Editor>(); //For BonePose CreationTools string createBonePoseAssetName = ""; bool applyAndResetOnCreateBP = true; //With DynamicDNAPlugins Update the editor for the DNA Converters (Skeleton Modifiers etc) no longer displays directly in the ConverterBehaviour //but is viewed in its own popup inspector (so it is clear to the user its a seperate asset). We still want to know if anything has been edited in there though //so we can do live updates to the avatar in play mode, so subscribe to OnLivePopupEditorChange so we get notified private void OnEnable() { DynamicDNAConverterControllerInspector.OnLivePopupEditorChange.RemoveListener(OnLiveConverterControllerChange); DynamicDNAConverterControllerInspector.OnLivePopupEditorChange.AddListener(OnLiveConverterControllerChange); } public void OnLiveConverterControllerChange() { thisDDCC = target as DynamicDNAConverterCustomizer; thisDDCC.UpdateUMA(); } public override void OnInspectorGUI() { thisDDCC = target as DynamicDNAConverterCustomizer; serializedObject.Update(); EditorGUILayout.PropertyField(serializedObject.FindProperty("dynamicDnaConverterPrefab")); EditorGUILayout.PropertyField(serializedObject.FindProperty("TposeAnimatorController")); EditorGUILayout.PropertyField(serializedObject.FindProperty("AposeAnimatorController")); EditorGUILayout.PropertyField(serializedObject.FindProperty("MovementAnimatorController")); if (Application.isPlaying) { EditorGUILayout.BeginHorizontal(); if (serializedObject.FindProperty("TposeAnimatorController").objectReferenceValue != null) { if (GUILayout.Button("Set T-Pose")) { thisDDCC.SetTPoseAni(); } } if (serializedObject.FindProperty("AposeAnimatorController").objectReferenceValue != null) { if (GUILayout.Button("Set A-Pose")) { thisDDCC.SetAPoseAni(); } } if (serializedObject.FindProperty("MovementAnimatorController").objectReferenceValue != null) { if (GUILayout.Button("Animate UMA")) { thisDDCC.SetMovementAni(); } } EditorGUILayout.EndHorizontal(); } EditorGUILayout.Space(); EditorGUILayout.PropertyField(serializedObject.FindProperty("targetUMA")); EditorGUILayout.PropertyField(serializedObject.FindProperty("guideUMA")); if(serializedObject.FindProperty("guideUMA").objectReferenceValue != null && Application.isPlaying) { EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Align Guide To Target")) { thisDDCC.AlignGuideToTarget(); } if (GUILayout.Button("Import Guide DNA Values")) { thisDDCC.ImportGuideDNAValues(); } EditorGUILayout.EndHorizontal(); } if (Application.isPlaying) { //UMA 2.8+ FixDNAPrefabs - this is a runtime only list of IDNAConverters now //SerializedProperty availableConvertersProp = serializedObject.FindProperty("availableConverters"); //SerializedProperty selectedConverterProp = serializedObject.FindProperty("selectedConverter"); List<string> availableConvertersPopup = new List<string>(); availableConvertersPopup.Add("None Selected"); int selectedConverterIndex = 0; int newSelectedConverterIndex = 0; /*for (int i = 0; i < availableConvertersProp.arraySize; i++) { availableConvertersPopup.Add(availableConvertersProp.GetArrayElementAtIndex(i).objectReferenceValue.name); if (selectedConverterProp.objectReferenceValue != null) if (availableConvertersProp.GetArrayElementAtIndex(i).objectReferenceValue.name == selectedConverterProp.objectReferenceValue.name) { selectedConverterIndex = i + 1; } }*/ for(int i = 0; i < thisDDCC.availableConverters.Count; i++) { if (!(thisDDCC.availableConverters[i] is IDynamicDNAConverter) || thisDDCC.availableConverters[i] == null) continue; availableConvertersPopup.Add(thisDDCC.availableConverters[i].name); if (thisDDCC.selectedConverter != null && thisDDCC.selectedConverter == thisDDCC.availableConverters[i]) selectedConverterIndex = i + 1; } EditorGUILayout.Space(); EditorGUI.BeginChangeCheck(); newSelectedConverterIndex = EditorGUILayout.Popup("Target UMA Converter", selectedConverterIndex, availableConvertersPopup.ToArray()); if (EditorGUI.EndChangeCheck()) { if (newSelectedConverterIndex != selectedConverterIndex) { if (newSelectedConverterIndex == 0) { thisDDCC.selectedConverter = null; } else { thisDDCC.selectedConverter = thisDDCC.availableConverters[newSelectedConverterIndex - 1]; } serializedObject.ApplyModifiedProperties();//Doesn't make sense now? thisDDCC.BackupConverter(); } } } if (thisDDCC.selectedConverter != null) { thisDDCC.StartListeningForUndo(); //import like this makes no sense now /* GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f, 0.3f)); EditorGUILayout.LabelField("Import Settings from another Converter", EditorStyles.boldLabel); var ImportFromConverterR = EditorGUILayout.GetControlRect(false); var ImportFromConverterLabelR = ImportFromConverterR; var ImportFromConverterFieldR = ImportFromConverterR; var ImportFromConverterButR = ImportFromConverterR; ImportFromConverterLabelR.width = 140; ImportFromConverterButR.width = 70; ImportFromConverterFieldR.width = ImportFromConverterFieldR.width - ImportFromConverterLabelR.width - ImportFromConverterButR.width; ImportFromConverterFieldR.x = ImportFromConverterLabelR.xMax; ImportFromConverterButR.x = ImportFromConverterFieldR.xMax + 5; EditorGUI.LabelField(ImportFromConverterLabelR, "Import from Converter"); EditorGUI.ObjectField(ImportFromConverterFieldR, serializedObject.FindProperty("converterToImport"), GUIContent.none); if (serializedObject.FindProperty("converterToImport").objectReferenceValue == null) EditorGUI.BeginDisabledGroup(true); if(GUI.Button(ImportFromConverterButR, "Import")) { if (thisDDCC.ImportConverterValues()) { serializedObject.FindProperty("converterToImport").objectReferenceValue = null; } } if (serializedObject.FindProperty("converterToImport").objectReferenceValue == null) EditorGUI.EndDisabledGroup(); GUIHelper.EndVerticalPadded(10); */ // Editor thisSDCB; if(SDCBs.TryGetValue(thisDDCC.selectedConverter, out thisSDCB)) { if (thisDDCC.selectedConverter is DynamicDNAConverterBehaviour) { ((DynamicDNAConverterBehaviourEditor)thisSDCB).initialized = true; } else if (thisDDCC.selectedConverter is DynamicDNAConverterController) { //Might need UMAData to work //((DynamicDNAConverterControllerInspector)thisSDCB) } } else { if (thisDDCC.selectedConverter is DynamicDNAConverterBehaviour) { thisSDCB = Editor.CreateEditor((thisDDCC.selectedConverter as DynamicDNAConverterBehaviour), typeof(DynamicDNAConverterBehaviourEditor)); SDCBs.Add(thisDDCC.selectedConverter, thisSDCB); } else if(thisDDCC.selectedConverter is DynamicDNAConverterController) { thisSDCB = Editor.CreateEditor((thisDDCC.selectedConverter as DynamicDNAConverterController), typeof(DynamicDNAConverterControllerInspector)); SDCBs.Add(thisDDCC.selectedConverter, thisSDCB); } } if (thisDDCC.selectedConverter is DynamicDNAConverterBehaviour) { ((DynamicDNAConverterBehaviourEditor)thisSDCB).thisDDCC = thisDDCC; ((DynamicDNAConverterBehaviourEditor)thisSDCB).umaData = thisDDCC.targetUMA.umaData; } else if(thisDDCC.selectedConverter is DynamicDNAConverterController) { } GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f, 0.3f)); EditorGUILayout.LabelField("Edit Values", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); thisSDCB.OnInspectorGUI(); if (EditorGUI.EndChangeCheck()) { thisDDCC.UpdateUMA(); } GUIHelper.EndVerticalPadded(10); //The following only makes sense for DynamicDNAConverterBehaviour right now //But we want to make them both work the same, and work the default Unity way //i.e. now we want to keep the changes by default and revert them if the user requests that //Altho changes to a component DONT get changed permanently in Play mode //and embedding the editor makes it LOOK LIKE we are editing a component if (thisDDCC.selectedConverter is DynamicDNAConverterBehaviour) { GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f, 0.3f)); EditorGUILayout.LabelField("Save Values", EditorStyles.boldLabel); Rect thisR = EditorGUILayout.GetControlRect(false); var thisButReset = thisR; var thisButSave = thisR; var thisButSaveNew = thisR; thisButReset.width = thisButSave.width = thisButSaveNew.width = (thisR.width / 3) - 2; thisButSave.x = thisButReset.xMax + 5; thisButSaveNew.x = thisButSave.xMax + 5; if (GUI.Button(thisButReset, new GUIContent("Reset", "Undo your changes to the currently selected converter"))) { thisDDCC.RestoreBackupVersion(serializedObject.FindProperty("selectedConverter").objectReferenceValue.name); } if (GUI.Button(thisButSave, new GUIContent("Save", "Save your changes to the currently selected converter"))) { thisDDCC.SaveChanges(); } if (GUI.Button(thisButSaveNew, new GUIContent("Save as New", "Save your changes to a new converter instance"))) { thisDDCC.SaveChangesAsNew(); } GUIHelper.EndVerticalPadded(10); } DrawBonePoseCreationTools(); } else { thisDDCC.StopListeningForUndo(); } serializedObject.ApplyModifiedProperties(); } private void DrawBonePoseCreationTools() { if (thisDDCC.targetUMA.umaData.skeleton != null) { GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f, 0.3f)); EditorGUILayout.LabelField("Create Poses from Current DNA state", EditorStyles.boldLabel); EditorGUILayout.HelpBox("Create bone poses from Avatar's current dna modified state. Applies the pose and sets DNA values back to 0.", MessageType.None); EditorGUILayout.HelpBox("Tip: Ensure all modifications you do not want included are turned off/set to default. In particular you will probably want to set 'Overall Modifiers' scale to 1 if you are planning to apply this in addition to the Pose later on.", MessageType.Info); EditorGUILayout.HelpBox("Smaller margin of error equals greater accuracy but creates more poses to apply on DNA Update.", MessageType.None); if (thisDDCC != null) { //[Range(0.000005f, 0.0005f)] EditorGUI.BeginChangeCheck(); var thisAccuracy = EditorGUILayout.Slider(new GUIContent("Margin Of Error", "The smaller the margin of error, the more accurate the Pose will be, but it will also have more bonePoses to apply when DNA is updated"), thisDDCC.bonePoseAccuracy * 1000, 0.5f, 0.005f); if (EditorGUI.EndChangeCheck()) { thisDDCC.bonePoseAccuracy = thisAccuracy / 1000; GUI.changed = false; } } createBonePoseAssetName = EditorGUILayout.TextField("New Bone Pose Name",createBonePoseAssetName); EditorGUILayout.HelpBox("Should the pose be applied and the dna values be reset to 0?", MessageType.None); applyAndResetOnCreateBP = EditorGUILayout.Toggle("Apply and Reset", applyAndResetOnCreateBP); GUILayout.BeginHorizontal(); GUILayout.Space(20); if (GUILayout.Button(/*createFromDnaButR, */"Create New BonePose Asset")) { if (thisDDCC != null) { if (thisDDCC.CreateBonePosesFromCurrentDna(createBonePoseAssetName, applyAndResetOnCreateBP)) { serializedObject.Update(); createBonePoseAssetName = ""; //this needs to repaint the plugins because their height of the reorderable list has changed now //cant figure out how to do that though } } } GUILayout.Space(20); GUILayout.EndHorizontal(); GUIHelper.EndVerticalPadded(10); } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // BatchedJoinBlock.cs // // // A propagator block that groups individual messages of multiple types // into tuples of arrays of those messages. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,>.DebugView))] public sealed class BatchedJoinBlock<T1, T2> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); if (!dataflowBlockOptions.Greedy) throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions)); if (dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) throw new ArgumentException(SR.Argument_BoundedCapacityNotSupported, nameof(dataflowBlockOptions)); Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>>> filter, out Tuple<IList<T1>, IList<T2>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); _target1.Complete(); _target2.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>> ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2> batchedJoinBlock) { Contract.Requires(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _batchedJoinBlock = batchedJoinBlock; _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> /// <typeparam name="T3">Specifies the type of data accepted by the block's third target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,,>.DebugView))] [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")] public sealed class BatchedJoinBlock<T1, T2, T3> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The target providing inputs of type T3.</summary> private readonly BatchedJoinBlockTarget<T3> _target3; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException(nameof(batchSize), SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException(nameof(dataflowBlockOptions)); if (!dataflowBlockOptions.Greedy || dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) { throw new ArgumentException(SR.Argument_NonGreedyNotSupported, nameof(dataflowBlockOptions)); } Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2, T3>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0 || _target3.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages(), _target3.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); _target3 = new BatchedJoinBlockTarget<T3>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2, T3>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2, T3>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2,T3}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <summary>Gets a target that may be used to offer messages of the third type.</summary> public ITargetBlock<T3> Target3 { get { return _target3; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>, IList<T3>>> filter, out Tuple<IList<T1>, IList<T2>, IList<T3>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>, IList<T3>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); Debug.Assert(_target3 != null, "_target3 not initialized"); _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>, IList<T3>> ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2, T3> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2, T3> batchedJoinBlock) { Contract.Requires(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); _batchedJoinBlock = batchedJoinBlock; } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>, IList<T3>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T3> Target3 { get { return _batchedJoinBlock._target3; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>, IList<T3>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } } namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Provides the target used in a BatchedJoin.</summary> /// <typeparam name="T">Specifies the type of data accepted by this target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlockTarget<>.DebugView))] internal sealed class BatchedJoinBlockTarget<T> : ITargetBlock<T>, IDebuggerDisplay { /// <summary>The shared resources used by all targets associated with the same batched join instance.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>Whether this target is declining future messages.</summary> private bool _decliningPermanently; /// <summary>Input messages for the next batch.</summary> private IList<T> _messages = new List<T>(); /// <summary>Initializes the target.</summary> /// <param name="sharedResources">The shared resources used by all targets associated with this batched join.</param> internal BatchedJoinBlockTarget(BatchedJoinBlockTargetSharedResources sharedResources) { Contract.Requires(sharedResources != null, "Targets require a shared resources through which to communicate."); // Store the shared resources, and register with it to let it know there's // another target. This is done in a non-thread-safe manner and must be done // during construction of the batched join instance. _sharedResources = sharedResources; sharedResources._remainingAliveTargets++; } /// <summary>Gets the number of messages buffered in this target.</summary> internal int Count { get { return _messages.Count; } } /// <summary>Gets the messages buffered by this target and then empties the collection.</summary> /// <returns>The messages from the target.</returns> internal IList<T> GetAndEmptyMessages() { Common.ContractAssertMonitorStatus(_sharedResources._incomingLock, held: true); IList<T> toReturn = _messages; _messages = new List<T>(); return toReturn; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { // If we've already stopped accepting messages, decline permanently if (_decliningPermanently || _sharedResources._decliningPermanently) return DataflowMessageStatus.DecliningPermanently; // Consume the message from the source if necessary, and store the message if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } _messages.Add(messageValue); // If this message makes a batch, notify the shared resources that a batch has been completed if (--_sharedResources._remainingItemsInBatch == 0) _sharedResources._batchSizeReachedAction(); return DataflowMessageStatus.Accepted; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { lock (_sharedResources._incomingLock) { // If this is the first time Complete is being called, // note that there's now one fewer targets receiving messages for the batched join. if (!_decliningPermanently) { _decliningPermanently = true; if (--_sharedResources._remainingAliveTargets == 0) _sharedResources._allTargetsDecliningPermanentlyAction(); } } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException(nameof(exception)); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { if (!_decliningPermanently && !_sharedResources._decliningPermanently) _sharedResources._exceptionAction(exception); } _sharedResources._completionAction(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0} InputCount={1}", Common.GetNameForDebugger(this), _messages.Count); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The batched join block target being viewed.</summary> private readonly BatchedJoinBlockTarget<T> _batchedJoinBlockTarget; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlockTarget">The batched join target being viewed.</param> public DebugView(BatchedJoinBlockTarget<T> batchedJoinBlockTarget) { Contract.Requires(batchedJoinBlockTarget != null, "Need a block with which to construct the debug view."); _batchedJoinBlockTarget = batchedJoinBlockTarget; } /// <summary>Gets the messages waiting to be processed.</summary> public IEnumerable<T> InputQueue { get { return _batchedJoinBlockTarget._messages; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _batchedJoinBlockTarget._decliningPermanently || _batchedJoinBlockTarget._sharedResources._decliningPermanently; } } } } /// <summary>Provides a container for resources shared across all targets used by the same BatchedJoinBlock instance.</summary> internal sealed class BatchedJoinBlockTargetSharedResources { /// <summary>Initializes the shared resources.</summary> /// <param name="batchSize">The size of a batch to create.</param> /// <param name="dataflowBlockOptions">The options used to configure the shared resources. Assumed to be immutable.</param> /// <param name="batchSizeReachedAction">The action to invoke when a batch is completed.</param> /// <param name="allTargetsDecliningAction">The action to invoke when no more targets are accepting input.</param> /// <param name="exceptionAction">The action to invoke when an exception needs to be logged.</param> /// <param name="completionAction">The action to invoke when completing, typically invoked due to a call to Fault.</param> internal BatchedJoinBlockTargetSharedResources( int batchSize, GroupingDataflowBlockOptions dataflowBlockOptions, Action batchSizeReachedAction, Action allTargetsDecliningAction, Action<Exception> exceptionAction, Action completionAction) { Debug.Assert(batchSize >= 1, "A positive batch size is required."); Debug.Assert(batchSizeReachedAction != null, "Need an action to invoke for each batch."); Debug.Assert(allTargetsDecliningAction != null, "Need an action to invoke when all targets have declined."); _incomingLock = new object(); _batchSize = batchSize; // _remainingAliveTargets will be incremented when targets are added. // They must be added during construction of the BatchedJoin<...>. _remainingAliveTargets = 0; _remainingItemsInBatch = batchSize; // Configure what to do when batches are completed and/or all targets start declining _allTargetsDecliningPermanentlyAction = () => { // Invoke the caller's action allTargetsDecliningAction(); // Don't accept any more messages. We should already // be doing this anyway through each individual target's declining flag, // so setting it to true is just a precaution and is also helpful // when onceOnly is true. _decliningPermanently = true; }; _batchSizeReachedAction = () => { // Invoke the caller's action batchSizeReachedAction(); _batchesCreated++; // If this batched join is meant to be used for only a single // batch, invoke the completion logic. if (_batchesCreated >= dataflowBlockOptions.ActualMaxNumberOfGroups) _allTargetsDecliningPermanentlyAction(); // Otherwise, get ready for the next batch. else _remainingItemsInBatch = _batchSize; }; _exceptionAction = exceptionAction; _completionAction = completionAction; } /// <summary> /// A lock used to synchronize all incoming messages on all targets. It protects all of the rest /// of the shared Resources's state and will be held while invoking the delegates. /// </summary> internal readonly object _incomingLock; /// <summary>The size of the batches to generate.</summary> internal readonly int _batchSize; /// <summary>The action to invoke when enough elements have been accumulated to make a batch.</summary> internal readonly Action _batchSizeReachedAction; /// <summary>The action to invoke when all targets are declining further messages.</summary> internal readonly Action _allTargetsDecliningPermanentlyAction; /// <summary>The action to invoke when an exception has to be logged.</summary> internal readonly Action<Exception> _exceptionAction; /// <summary>The action to invoke when the owning block has to be completed.</summary> internal readonly Action _completionAction; /// <summary>The number of items remaining to form a batch.</summary> internal int _remainingItemsInBatch; /// <summary>The number of targets still alive (i.e. not declining all further messages).</summary> internal int _remainingAliveTargets; /// <summary>Whether all targets should decline all further messages.</summary> internal bool _decliningPermanently; /// <summary>The number of batches created.</summary> internal long _batchesCreated; } }
namespace Microsoft.Protocols.TestSuites.MS_FSSHTTP_FSSHTTPB { using System; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.SharedAdapter; using Microsoft.Protocols.TestSuites.SharedTestSuite; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// A class which contains test cases used to verify the co-authoring sub request operation. /// </summary> [TestClass] public sealed class MS_FSSHTTP_FSSHTTPB_S02_Coauth : S02_Coauth { #region Test Suite Initialization and clean up /// <summary> /// Class initialization /// </summary> /// <param name="testContext">The context of the test suite.</param> [ClassInitialize] public static new void ClassInitialize(TestContext testContext) { S02_Coauth.ClassInitialize(testContext); } /// <summary> /// Class clean up /// </summary> [ClassCleanup] public static new void ClassCleanup() { S02_Coauth.ClassCleanup(); } #endregion /// <summary> /// A method used to verify the related requirements when the URL attribute of the corresponding Request element doesn't exist. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC01_JoinCoauthoringSession_UrlNotSpecified() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a JoinCoauthoringSession subRequest with all valid parameters. CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID); CellStorageResponse response = new CellStorageResponse(); bool isR3006Verified = false; try { // Send a JoinCoauthoringSession subRequest to the protocol server without specifying URL attribute. response = this.Adapter.CellStorageRequest(null, new SubRequestType[] { subRequest }); } catch (System.Xml.XmlException exception) { string message = exception.Message; isR3006Verified = message.Contains("Duplicate attribute"); isR3006Verified &= message.Contains("ErrorCode"); } if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3006 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.CaptureRequirementIfIsTrue( isR3006Verified, "MS-FSSHTTP", 3006, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element."); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3007 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site)) { Site.CaptureRequirementIfIsNull( response.ResponseCollection, "MS-FSSHTTP", 3007, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3006, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.Assert.IsTrue( isR3006Verified, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); } if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3007, this.Site)) { Site.Assert.IsNull( response.ResponseCollection, @"[In Appendix B: Product Behavior] If the URL attribute of the corresponding Request element doesn't exist, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); } } } /// <summary> /// A method used to verify the related requirements when the URL attribute of the corresponding Request element is an empty string. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC02_JoinCoauthoringSession_EmptyUrl() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Create a JoinCoauthoringSession subRequest with all valid parameters. CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID); CellStorageResponse response = new CellStorageResponse(); bool isR3008Verified = false; try { // Send a JoinCoauthoringSession subRequest to the protocol server with empty Url attribute. response = this.Adapter.CellStorageRequest(string.Empty, new SubRequestType[] { subRequest }); } catch (System.Xml.XmlException exception) { string message = exception.Message; isR3008Verified = message.Contains("Duplicate attribute"); isR3008Verified &= message.Contains("ErrorCode"); } if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3008 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is empty."); Site.CaptureRequirementIfIsTrue( isR3008Verified, "MS-FSSHTTP", 3008, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does return two ErrorCode attributes in Response element. <11> Section 2.2.3.5: SharePoint Server 2010 will return 2 ErrorCode attributes in Response element."); } // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R3009 if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site)) { Site.CaptureRequirementIfIsNull( response.ResponseCollection, "MS-FSSHTTP", 3009, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <11> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); Site.CaptureRequirementIfAreEqual<GenericErrorCodeTypes>( GenericErrorCodeTypes.InvalidUrl, response.ResponseVersion.ErrorCode, "MS-FSSHTTP", 11071, @"[In GenericErrorCodeTypes] InvalidUrl indicates an error when the associated protocol server site URL is empty."); } } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3008, this.Site)) { Site.Log.Add( LogEntryKind.Debug, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); Site.Assert.IsTrue( isR3008Verified, "SharePoint server 2010 and SharePoint Foundation responses two ErrorCode attributes when the URL is non exists."); } if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 3009, this.Site)) { Site.Assert.IsNull( response.ResponseCollection, @"[In Appendix B: Product Behavior] If the Url attribute of the corresponding Request element is an empty string, the implementation does not return Response element. <8> Section 2.2.3.5: SharePoint Server 2013 will not return Response element."); Site.Assert.AreNotEqual<GenericErrorCodeTypes>( GenericErrorCodeTypes.InvalidUrl, response.ResponseVersion.ErrorCode, @"[In GenericErrorCodeTypes] InvalidUrl indicates an error when the associated protocol server site URL is empty."); } } } /// <summary> /// A method used to verify the response information when executing operation JoinCoauthoringSession, RefreshCoauthoringSession, CheckLockAvailability on a file which has been checked out by different user account. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC03_CoauthSubRequest_FileAlreadyCheckedOutOnServer() { // Use SUT method to check out the file. if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName02, this.Password02, this.Domain)) { this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password {2}", this.DefaultFileUrl, this.UserName02, this.Password02); } this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName02, this.Password02, this.Domain); // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Join a Coauthoring session, if the coauthorable file is checked out on the server and is checked out by a client with a different user name, the server returns a FileAlreadyCheckedOutOnServer error code. // Now the web service is initialized using the user01, so the user is different with the user who check the file out. CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID); CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest }); CoauthSubResponseType joinResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1555 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), "MS-FSSHTTP", 1555, @"[In Join Coauthoring Session] If the coauthorable file is checked out on the server and checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), @"[When sending Join Coauthoring Session subrequest] If the coauthorable file is checked out on the server and checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } bool isVerifyR385 = joinResponse.ErrorMessage != null && joinResponse.ErrorMessage.IndexOf(this.UserName02, StringComparison.OrdinalIgnoreCase) >= 0; if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { this.Site.Log.Add( LogEntryKind.Debug, "For the requirement MS-FSSHTTP_R385, the error message should contain the user name {0}, actual value is {1}", this.UserName02, joinResponse.ErrorMessage); Site.CaptureRequirementIfIsTrue( isVerifyR385, "MS-FSSHTTP", 385, @"[In LockAndCoauthRelatedErrorCodeTypes][FileAlreadyCheckedOutOnServer] When the ""FileAlreadyCheckedOutOnServer"" error code is returned as the error code value in the SubResponse element, the protocol server returns the identity of the user who has currently checked out the file in the error message attribute."); } else { this.Site.Log.Add( LogEntryKind.Debug, "The error message should contain the user name {0}, actual value is {1}", this.UserName02, joinResponse.ErrorMessage); Site.Assert.IsTrue( isVerifyR385, @"When the ""FileAlreadyCheckedOutOnServer"" error code is returned as the error code value in the SubResponse element, the protocol server returns the identity of the user who has currently checked out the file in the error message attribute."); } // Refresh the Coauthoring Session, if the coauthorable file is checked out on the server and is checked out by a client with a different user name, // the server returns a FileAlreadyCheckedOutOnServer error code. subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForRefreshCoauthoringSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID); cellResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest }); CoauthSubResponseType refreshResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); isVerifyR385 = refreshResponse.ErrorMessage != null && refreshResponse.ErrorMessage.IndexOf(this.UserName02, StringComparison.OrdinalIgnoreCase) >= 0; if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 1566, this.Site)) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1566 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(refreshResponse.ErrorCode, this.Site), "MS-FSSHTTP", 1566, @"[In Refresh Coauthoring Session][When sending Refresh Coauthoring Session subrequest] If the coauthorable file is checked out on the server and checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } this.Site.Log.Add( LogEntryKind.Debug, "For the requirement MS-FSSHTTP_R385, the error message should contain the user name {0}, actual value is {1}", this.UserName02, refreshResponse.ErrorMessage); Site.CaptureRequirementIfIsTrue( isVerifyR385, "MS-FSSHTTP", 385, @"[In LockAndCoauthRelatedErrorCodeTypes][FileAlreadyCheckedOutOnServer] When the ""FileAlreadyCheckedOutOnServer"" error code is returned as the error code value in the SubResponse element, the protocol server returns the identity of the user who has currently checked out the file in the error message attribute."); } else { if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 1566, this.Site)) { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(refreshResponse.ErrorCode, this.Site), @"[When sending Refresh Coauthoring Session subrequest]If the coauthorable file is checked out on the server and checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } this.Site.Log.Add( LogEntryKind.Debug, "The error message should contain the user name {0}, actual value is {1}", this.UserName02, refreshResponse.ErrorMessage); Site.Assert.IsTrue( isVerifyR385, @"When the ""FileAlreadyCheckedOutOnServer"" error code is returned as the error code value in the SubResponse element, the protocol server returns the identity of the user who has currently checked out the file in the error message attribute."); } // Check Lock Availability of the Coauthoring Session, if the file is already checked out by a different user, // the server returns a FileAlreadyCheckedOutOnServer error code. subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForCheckLockAvailability(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID); cellResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { subRequest }); CoauthSubResponseType checkResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); // Add the log information. Site.Log.Add(LogEntryKind.Debug, "The errorCode for Check Lock Availability SubRequest is :{0}", checkResponse.ErrorCode); if (Common.IsRequirementEnabled("MS-FSSHTTP-FSSHTTPB", 1082, this.Site)) { if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R1082 Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(checkResponse.ErrorCode, this.Site), "MS-FSSHTTP", 1082, @"[In Check Lock Availability] If the coauthorable file is checked out on the server and it is checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.FileAlreadyCheckedOutOnServer, SharedTestSuiteHelper.ConvertToErrorCodeType(checkResponse.ErrorCode, this.Site), @"[When sending check lock availability subrequest]If the coauthorable file is checked out on the server and it is checked out by a client with a different user name than the current client, the protocol server returns an error code value set to ""FileAlreadyCheckedOutOnServer""."); } } } /// <summary> /// A method used to verify that only the clients which have the same schema lock identifier can lock the file. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC04_JoinCoauthSession_FileNotExistsOrCannotBeCreated() { // Join a coauthoring session on a nonexistent file, expect the server returns the error code "FileNotExistsOrCannotBeCreated". string fileUrlNotExit = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site); // Initialize the service this.InitializeContext(fileUrlNotExit, this.UserName01, this.Password01, this.Domain); // Join a Coauthoring session with the non-exist URL. CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID, null, null, 3600); CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(fileUrlNotExit, new SubRequestType[] { subRequest }); CoauthSubResponseType joinResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // If the ErrorCode attribute returned equals "FileNotExistsOrCannotBeCreated", MS-FSSHTTP_R4003 can be covered. Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.FileNotExistsOrCannotBeCreated, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), "MS-FSSHTTP", 4003, @"[In Coauth Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element."); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.FileNotExistsOrCannotBeCreated, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), @"[In Coauth Subrequest][The protocol server returns results based on the following conditions:] If the protocol server was unable to find the URL for the file specified in the Url attribute, the protocol server reports a failure by returning an error code value set to ""FileNotExistsOrCannotBeCreated"" in the ErrorCode attribute sent back in the SubResponse element."); } } /// <summary> /// A method used to verify that the protocol server returns an ExclusiveLockReturnReasonTypes attribute value set to "CheckedOutByCurrentUser" when the file is checked out by the current user who sent the cell storage service request message. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC05_JoinCoauthoringSession_CheckedOutByCurrentUser() { // Initialize the service this.InitializeContext(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); // Check out the file if (!this.SutManagedAdapter.CheckOutFile(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain)) { this.Site.Assert.Fail("Cannot change the file {0} to check out status using the user name {1} and password {2}", this.DefaultFileUrl, this.UserName01, this.Password01); } this.StatusManager.RecordFileCheckOut(this.DefaultFileUrl, this.UserName01, this.Password01, this.Domain); CheckLockAvailability(); // Join a Coauthoring session CoauthSubRequestType request = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID, true, SharedTestSuiteHelper.DefaultExclusiveLockID); CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(this.DefaultFileUrl, new SubRequestType[] { request }); CoauthSubResponseType response = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); this.Site.Assert.AreEqual( ErrorCodeType.Success, SharedTestSuiteHelper.ConvertToErrorCodeType(response.ErrorCode, this.Site), "The test case cannot continue unless the server response succeeds when the user join the coauthoring session with allowFallback set to true on an already checked out file by the same user."); this.StatusManager.RecordExclusiveLock(this.DefaultFileUrl, SharedTestSuiteHelper.DefaultExclusiveLockID); this.Site.Assert.AreEqual( "ExclusiveLock", response.SubResponseData.LockType, "The test case cannot continue unless the server responses an exclusive lock type when the user join the coauthoring session with allowFallback set to true on an already checked out file by the same user."); this.Site.Assert.IsTrue( response.SubResponseData.ExclusiveLockReturnReasonSpecified, "The test case cannot continue unless the server returns ExclusiveLockReturnReason attribute when the user join the coauthoring session with allowFallback set to true on an already checked out file by the same user."); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { // Verify MS-FSSHTTP requirement: MS-FSSHTTP_R350 Site.CaptureRequirementIfAreEqual<ExclusiveLockReturnReasonTypes>( ExclusiveLockReturnReasonTypes.CheckedOutByCurrentUser, response.SubResponseData.ExclusiveLockReturnReason, "MS-FSSHTTP", 350, @"[In ExclusiveLockReturnReasonTypes] CheckedOutByCurrentUser: The string value ""CheckedOutByCurrentUser"", indicating that an exclusive lock is granted on the file because the file is checked out by the current user who sent the cell storage service request message."); } else { Site.Assert.AreEqual<ExclusiveLockReturnReasonTypes>( ExclusiveLockReturnReasonTypes.CheckedOutByCurrentUser, response.SubResponseData.ExclusiveLockReturnReason, "The server should response when an exclusive lock is granted on the file because the file is checked out by the current user who sent the cell storage service request message."); } } /// <summary> /// A method used to verify the related requirements when the file path is not found. /// </summary> [TestCategory("MSFSSHTTP_FSSHTTPB"), TestMethod()] public void MSFSSHTTP_FSSHTTPB_S02_TC06_JoinCoauthoringSession_PathNotFound() { Site.Assume.IsTrue(Common.IsRequirementEnabled(11265, this.Site), "This test case only runs PathNotFound is returned when the file path is not found."); string fileUrlNotExit = SharedTestSuiteHelper.GenerateNonExistFileUrl(this.Site); string path = fileUrlNotExit.Substring(0, fileUrlNotExit.LastIndexOf('/')); // Initialize the service this.InitializeContext(path, this.UserName01, this.Password01, this.Domain); CoauthSubRequestType subRequest = SharedTestSuiteHelper.CreateCoauthSubRequestForJoinCoauthSession(SharedTestSuiteHelper.DefaultClientID, SharedTestSuiteHelper.ReservedSchemaLockID, null, null, 3600); CellStorageResponse cellResponse = this.Adapter.CellStorageRequest(path, new SubRequestType[] { subRequest }); CoauthSubResponseType joinResponse = SharedTestSuiteHelper.ExtractSubResponse<CoauthSubResponseType>(cellResponse, 0, 0, this.Site); if (SharedContext.Current.IsMsFsshttpRequirementsCaptured) { Site.CaptureRequirementIfAreEqual<ErrorCodeType>( ErrorCodeType.PathNotFound, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), "MS-FSSHTTP", 11265, @"[In Appendix B: Product Behavior] Implementation does return the value ""PathNotFound"" of GenericErrorCodeTypes when the file path is not found. (Microsoft Office 2016/Microsoft SharePoint Server 2016 follow this behavior.)"); } else { Site.Assert.AreEqual<ErrorCodeType>( ErrorCodeType.PathNotFound, SharedTestSuiteHelper.ConvertToErrorCodeType(joinResponse.ErrorCode, this.Site), @"Error ""PathNotFound"" should be returned when the file path is not found."); } } /// <summary> /// Initialize the shared context based on the specified request file URL, user name, password and domain for the MS-FSSHTTP test purpose. /// </summary> /// <param name="requestFileUrl">Specify the request file URL.</param> /// <param name="userName">Specify the user name.</param> /// <param name="password">Specify the password.</param> /// <param name="domain">Specify the domain.</param> protected override void InitializeContext(string requestFileUrl, string userName, string password, string domain) { SharedContextUtils.InitializeSharedContextForFSSHTTP(userName, password, domain, this.Site); } /// <summary> /// Merge the common configuration and should/may configuration file. /// </summary> /// <param name="site">An instance of interface ITestSite which provides logging, assertions, /// and adapters for test code onto its execution context.</param> protected override void MergeConfigurationFile(TestTools.ITestSite site) { ConfigurationFileHelper.MergeConfigurationFile(site); } } }
/* ==================================================================== 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 is1 distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.HSSF { using System; using System.IO; using System.Text; using NPOI.HSSF.UserModel; /** * Centralises logic for finding/Opening sample files in the src/testcases/org/apache/poi/hssf/hssf/data folder. * * @author Josh Micich */ public class HSSFTestDataSamples { private static String TEST_DATA_DIR_SYS_PROPERTY_NAME = "HSSF.testdata.path"; private static string _resolvedDataDir; /** <code>true</code> if standard system propery is1 not set, * but the data is1 available on the test runtime classpath */ private static bool _sampleDataIsAvaliableOnClassPath; /** * Opens a sample file from the standard HSSF test data directory * * @return an Open <tt>Stream</tt> for the specified sample file */ public static Stream OpenSampleFileStream(String sampleFileName) { Initialise(); if (_sampleDataIsAvaliableOnClassPath) { Stream result = OpenClasspathResource(sampleFileName); if (result == null) { throw new Exception("specified test sample file '" + sampleFileName + "' not found on the classpath"); } // System.out.println("Opening cp: " + sampleFileName); // wrap to avoid temp warning method about auto-closing input stream return new NonSeekableStream(result); } if (_resolvedDataDir == "") { throw new Exception("Must set system property '" + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' properly before running tests"); } if (!File.Exists(_resolvedDataDir+sampleFileName)) { throw new Exception("Sample file '" + sampleFileName + "' not found in data dir '" + _resolvedDataDir + "'"); } // System.out.println("Opening " + f.GetAbsolutePath()); try { return new FileStream(_resolvedDataDir+sampleFileName,FileMode.Open); } catch (FileNotFoundException) { throw; } } private static void Initialise() { String dataDirName = System.Configuration.ConfigurationSettings.AppSettings[TEST_DATA_DIR_SYS_PROPERTY_NAME]; if(dataDirName=="") throw new Exception("Must set system property '" + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' before running tests"); if (!Directory.Exists(dataDirName)) { throw new IOException("Data dir '" + dataDirName + "' specified by system property '" + TEST_DATA_DIR_SYS_PROPERTY_NAME + "' does not exist"); } _sampleDataIsAvaliableOnClassPath = true; _resolvedDataDir = dataDirName; } /** * Opens a test sample file from the 'data' sub-package of this class's package. * @return <code>null</code> if the sample file is1 not deployed on the classpath. */ private static Stream OpenClasspathResource(String sampleFileName) { FileStream file = new FileStream(System.Configuration.ConfigurationSettings.AppSettings["HSSF.testdata.path"] + sampleFileName, FileMode.Open); return file; } private class NonSeekableStream : Stream { private Stream _is; public NonSeekableStream(Stream is1) { _is = is1; } public int Read() { return _is.ReadByte(); } public override int Read(byte[] b, int off, int len) { return _is.Read(b, off, len); } public bool markSupported() { return false; } public override void Close() { _is.Close(); } public override bool CanRead { get { return _is.CanRead; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return _is.CanWrite; } } public override long Length { get { return _is.Length; } } public override long Position { get { return _is.Position; } set { _is.Position = value; } } public override void Write(byte[] buffer, int offset, int count) { _is.Write(buffer, offset, count); } public override void Flush() { _is.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return _is.Seek(offset, origin); } public override void SetLength(long value) { _is.SetLength(value); } } public static HSSFWorkbook OpenSampleWorkbook(String sampleFileName) { try { return new HSSFWorkbook(OpenSampleFileStream(sampleFileName)); } catch (IOException) { throw; } } /** * Writes a spReadsheet to a <tt>MemoryStream</tt> and Reads it back * from a <tt>ByteArrayStream</tt>.<p/> * Useful for verifying that the serialisation round trip */ public static HSSFWorkbook WriteOutAndReadBack(HSSFWorkbook original) { try { MemoryStream baos = new MemoryStream(4096); original.Write(baos); return new HSSFWorkbook(baos); } catch (IOException) { throw; } } /** * @return byte array of sample file content from file found in standard hssf test data dir */ public static byte[] GetTestDataFileContent(String fileName) { MemoryStream bos = new MemoryStream(); try { Stream fis = HSSFTestDataSamples.OpenSampleFileStream(fileName); byte[] buf = new byte[512]; while (true) { int bytesRead = fis.Read(buf,0,buf.Length); if (bytesRead < 1) { break; } bos.Write(buf, 0, bytesRead); } fis.Close(); } catch (IOException) { throw; } return bos.ToArray(); } } }
using Xunit; using Moq; using PreMailer.Net.Downloaders; using System; using System.IO; namespace PreMailer.Net.Tests { public class PreMailerTests { [Fact] public void MoveCssInline_HasStyle_DoesNotBreakImageWidthAttribute() { string input = "<html><head><style type=\"text/css\">img { }</style></head>" + "<body><img style=\"width: 206px; height: 64px;\" src=\"http://localhost/left.gif\" height=\"64\" WIDTH=\"206\" border=\"0\"></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.DoesNotContain("width=\"206px\"", premailedOutput.Html); Assert.Contains("width=\"206\"", premailedOutput.Html); } [Fact] public void MoveCssInline_NoStyle_DoesNotBreakImageWidthAttribute() { string input = "<html><head><style type=\"text/css\"></style></head>" + "<body><img style=\"width: 206px; height: 64px;\" src=\"http://localhost/left.gif\" height=\"64\" WIDTH=\"206\" border=\"0\"></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.DoesNotContain("width=\"206px\"", premailedOutput.Html); Assert.Contains("width=\"206\"", premailedOutput.Html); } [Fact] public void MoveCssInline_RespectExistingStyleElement() { string input = "<html><head><style type=\"text/css\">.test { height: 100px; }</style></head><body><div class=\"test\" style=\"width: 100px;\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("<div class=\"test\" style=\"height: 100px;width: 100px", premailedOutput.Html); } [Fact] public void MoveCssInline_InlineStyleElementTakesPrecedence() { string input = "<html><head><style type=\"text/css\">.test { width: 150px; }</style></head><body><div class=\"test\" style=\"width: 100px;\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("<div class=\"test\" style=\"width: 100px", premailedOutput.Html); } [Fact] public void MoveCssInline_CssWithHigherSpecificity_AppliesMoreSpecificCss() { string input = "<html><head><style type=\"text/css\">#high-imp.test { width: 42px; } .test { width: 150px; }</style></head><body><div id=\"high-imp\" class=\"test\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("style=\"width: 42px\"", premailedOutput.Html); } [Fact] public void MoveCssInline_CssWithHigherSpecificityInSeparateStyleTag_AppliesMoreSpecificCss() { string input = "<html><head><style type=\"text/css\">.target { width: 42px; }</style><style type=\"text/css\">.outer .inner .target { width: 1337px; }</style></head><body><div class=\"outer\"><div class=\"inner\"><div class=\"target\">test</div></div></div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("style=\"width: 1337px\"", premailedOutput.Html); } [Fact] public void MoveCssInline_IgnoreStyleElement_DoesntApplyCss() { string input = "<html><head><style type=\"text/css\">.target { width: 42px; }</style><style type=\"text/css\" id=\"ignore\">.target { width: 1337px; }</style></head><body><div class=\"outer\"><div class=\"inner\"><div class=\"target\">test</div></div></div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false, ignoreElements: "#ignore"); Assert.Contains("style=\"width: 42px\"", premailedOutput.Html); } [Fact] public void MoveCssInline_SupportedPseudoSelector_AppliesCss() { string input = "<html><head><style type=\"text/css\">li:first-child { width: 42px; }</style></head><body><ul><li>target</li><li>blargh></li></ul></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<li style=\"width: 42px\">", premailedOutput.Html); } [Fact] public void MoveCssInline_CrazyCssSelector_DoesNotThrowError() { string input = "<html><head><style type=\"text/css\">li:crazy { width: 42px; }</style></head><body><ul><li>target</li><li>blargh></li></ul></body></html>"; try { PreMailer.MoveCssInline(input); } catch (Exception ex) { Assert.True(false, ex.Message); } } [Fact] public void MoveCssInline_SupportedjQuerySelector_AppliesCss() { string input = "<html><head><style type=\"text/css\">li:first-child { width: 42px; }</style></head><body><ul><li>target</li><li>blargh></li></ul></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<li style=\"width: 42px\">target</li>", premailedOutput.Html); } [Fact] public void MoveCssInline_UnsupportedSelector_AppliesCss() { string input = "<html><head><style type=\"text/css\">p:first-letter { width: 42px; }</style></head><body><p>target</p></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<p>target</p>", premailedOutput.Html); } [Fact] public void MoveCssInline_KeepStyleElementsIgnoreElementsMatchesStyleElement_DoesntRemoveScriptTag() { string input = "<html><head><style id=\"ignore\" type=\"text/css\">li:before { width: 42px; }</style></head><body><div class=\"target\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, removeStyleElements: false, ignoreElements: "#ignore"); Assert.Contains("<style id=\"ignore\" type=\"text/css\">", premailedOutput.Html); } [Fact] public void MoveCssInline_PreserveMediaQueries_RemovesStyleElementsWithoutMediaQueries() { string input = "<html><head><style>div { width: 42px; }</style></head><body><div>test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, removeStyleElements: true, preserveMediaQueries: true); Assert.DoesNotContain("<style>", premailedOutput.Html); } [Fact] public void MoveCssInline_PreserveMediaQueries_PreservesStyleElementsWithMediaQueries() { string input = "<html><head><style>div { width: 42px; } @media (max-width: 250px) { div { width: 20px; } }</style></head><body><div>test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, removeStyleElements: true, preserveMediaQueries: true); Assert.Contains("<style>@media (max-width: 250px) { div { width: 20px; } }</style>", premailedOutput.Html); } [Fact] public void MoveCssInline_MultipleSelectors_HonorsIndividualSpecificity() { string input = "<html><head><style type=\"text/css\">p,li,tr.pub-heading td,tr.pub-footer td,tr.footer-heading td { font-size: 12px; line-height: 16px; } td.disclaimer p {font-size: 11px;} </style></head><body><table><tr class=\"pub-heading\"><td class=\"disclaimer\"><p></p></td></tr></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<p style=\"line-height: 16px;font-size: 11px\"></p>", premailedOutput.Html); } [Fact] public void MoveCssInline_ImportantFlag_HonorsImportantFlagInStylesheet() { string input = "<style>div { color: blue !important; }</style><div style=\"color: red\">Red</div>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<div style=\"color: blue", premailedOutput.Html); } [Fact] public void MoveCssInline_ImportantFlag_HonorsImportantFlagInline() { string input = "<style>div { color: blue !important; }</style><div style=\"color: red !important\">Red</div>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<div style=\"color: red", premailedOutput.Html); } [Fact] public void MoveCssInline_AbsoluteBackgroundUrl_ShouldNotBeCleanedAsComment() { string input = "<style>div { background: url('http://my.web.site.com/Content/email/content.png') repeat-y }</style><div></div>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<div style=\"background: url('http://my.web.site.com/Content/email/content.png') repeat-y\"></div>", premailedOutput.Html); } [Fact] public void MoveCssInline_SupportedMediaAttribute_InlinesAsNormal() { string input = "<html><head><style type=\"text/css\" media=\"screen\">div { width: 100% }</style></head><body><div>Target</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<div style=\"width: 100%\">Target</div>", premailedOutput.Html); } [Fact] public void MoveCssInline_UnsupportedMediaAttribute_IgnoresStyles() { string input = "<html><head><style type=\"text/css\" media=\"print\">div { width: 100% }</style></head><body><div>Target</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input); Assert.Contains("<div>Target</div>", premailedOutput.Html); } [Fact] public void MoveCssInline_AddBgColorStyle() { string input = "<html><head><style type=\"text/css\">.test { background-color:#f1f1f1; }</style></head><body><table><tr><td class=\"test\" bgcolor=\"\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("<td class=\"test\" bgcolor=\"#f1f1f1\" style=\"background-color: #f1f1f1\">", premailedOutput.Html); } [Fact] public void MoveCssInline_AddSpecial() { string input = "<html><head><style type=\"text/css\">.test { padding: 7px; -premailer-cellspacing: 5; -premailer-width: 14%; }</style></head><body><table><tr><td class=\"test\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.True(premailedOutput.Html.Contains("<td class=\"test\" style=\"padding: 7px\" cellspacing=\"5\" width=\"14%\">"), "Actual: " + premailedOutput.Html); } [Fact] public void MoveCssInline_AddSpecial_RemoveEmptyStyle() { string input = "<html><head><style type=\"text/css\">.test { -premailer-cellspacing: 5; -premailer-width: 14%; }</style></head><body><table><tr><td class=\"test\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.True(premailedOutput.Html.Contains("<td class=\"test\" cellspacing=\"5\" width=\"14%\">"), "Actual: " + premailedOutput.Html); } [Fact] public void MoveCssInline_AddBgColorStyle_IgnoreElementWithBackgroundColorAndNoBgColor() { string input = "<html><head><style type=\"text/css\">.test { background-color:#f1f1f1; }</style></head><body><table><tr><td class=\"test\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("<td class=\"test\" style=\"background-color: #f1f1f1\"", premailedOutput.Html); } [Fact] public void MoveCssInline_NoStyleElement_StylesGivenInCSSParam_InlinesThat() { string input = "<html><head></head><body><table><tr><td class=\"test\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false, css: ".test { background-color:#f1f1f1; }"); Assert.Contains("<td class=\"test\" style=\"background-color: #f1f1f1\"", premailedOutput.Html); } [Fact] public void MoveCssInline_StripsClassAttributes() { string input = "<html><head></head><body><table id=\"testTable\"><tr><td class=\"test\"></td></tr></table></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false, css: ".test { background-color:#f1f1f1; }", stripIdAndClassAttributes: true); Assert.Contains("<td style=\"background-color: #f1f1f1\"", premailedOutput.Html); } [Fact] public void MoveCssInline_StripsIdAttributes() { string input = "<html><head><style type=\"text/css\">#high-imp.test { width: 42px; } .test { width: 150px; }</style></head><body><div id=\"high-imp\" class=\"test\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false, stripIdAndClassAttributes: true); Assert.Contains("<div style=\"width: 42px\">", premailedOutput.Html); } [Fact] public void MoveCssInline_StripsComments() { string input = "<html><head></head><body><!--This should be removed--></body></html>"; string expected = "<html><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, removeComments: true); Assert.True(expected == premailedOutput.Html); } [Fact] public void MoveCssInline_LaterPositionStylesWithEqualSpecificityHasPrecedence_InSameBlock() { string input1 = "<html><head><style type=\"text/css\">table.acolor td { color: #0F0; } table.bcolor td { color: #00F; }</style></head><body><table class=\"acolor bcolor\"><tr><td>test</td></tr></table></body></html>"; string input2 = "<html><head><style type=\"text/css\">table.bcolor td { color: #00F; } table.acolor td { color: #0F0; }</style></head><body><table class=\"acolor bcolor\"><tr><td>test</td></tr></table></body></html>"; var premailedOutput1 = PreMailer.MoveCssInline(input1, false); var premailedOutput2 = PreMailer.MoveCssInline(input2, false); Assert.Contains("<td style=\"color: #00F\">test</td>", premailedOutput1.Html); Assert.Contains("<td style=\"color: #0F0\">test</td>", premailedOutput2.Html); } [Fact] public void MoveCssInline_LaterPositionStylesWithEqualSpecificityHasPrecedence_Nested_InSameBlock() { string input1 = "<html><head><style type=\"text/css\">table.child td { color: #00F; } table.parent td { color: #0F0; }</style></head><body><table class=\"parent\"><tr><td><table class=\"child\"><tr><td>test</td></tr></table></td></tr></table></body></html>"; string input2 = "<html><head><style type=\"text/css\">table.parent td { color: #0F0; } table.child td { color: #00F; }</style></head><body><table class=\"parent\"><tr><td><table class=\"child\"><tr><td>test</td></tr></table></td></tr></table></body></html>"; var premailedOutput1 = PreMailer.MoveCssInline(input1, false); var premailedOutput2 = PreMailer.MoveCssInline(input2, false); Assert.Contains("<td style=\"color: #0F0\">test</td>", premailedOutput1.Html); Assert.Contains("<td style=\"color: #00F\">test</td>", premailedOutput2.Html); } [Fact] public void MoveCssInline_LaterPositionStylesWithEqualSpecificityHasPrecedence_InSeparateBlocks() { string input1 = "<html><head><style type=\"text/css\">table.acolor td { color: #00F; }</style><style type=\"text/css\">table.bcolor td { color: #0F0; }</style></head><body><table class=\"acolor bcolor\"><tr><td>test</td></tr></table></body></html>"; string input2 = "<html><head><style type=\"text/css\">table.bcolor td { color: #0F0; }</style><style type=\"text/css\">table.acolor td { color: #00F; }</style></head><body><table class=\"acolor bcolor\"><tr><td>test</td></tr></table></body></html>"; var premailedOutput1 = PreMailer.MoveCssInline(input1, false); var premailedOutput2 = PreMailer.MoveCssInline(input2, false); Assert.Contains("<td style=\"color: #0F0\">test</td>", premailedOutput1.Html); Assert.Contains("<td style=\"color: #00F\">test</td>", premailedOutput2.Html); } [Fact] public void MoveCssInline_LaterPositionStylesWithEqualSpecificityHasPrecedence_Nested_InSeparateBlocks() { string input1 = "<html><head><style type=\"text/css\">table.child td { color: #00F; } table.parent td { color: #00F; }</style><style type=\"text/css\">table.parent td { color: #0F0; }</style></head><body><table class=\"parent\"><tr><td><table class=\"child\"><tr><td>test</td></tr></table></td></tr></table></body></html>"; string input2 = "<html><head><style type=\"text/css\">table.parent td { color: #0F0; } table.child td { color: #0F0; }</style><style type=\"text/css\">table.child td { color: #00F; }</style></head><body><table class=\"parent\"><tr><td><table class=\"child\"><tr><td>test</td></tr></table></td></tr></table></body></html>"; var premailedOutput1 = PreMailer.MoveCssInline(input1, false); var premailedOutput2 = PreMailer.MoveCssInline(input2, false); Assert.Contains("<td style=\"color: #0F0\">test</td>", premailedOutput1.Html); Assert.Contains("<td style=\"color: #00F\">test</td>", premailedOutput2.Html); } [Fact] public void AddAnalyticsTags_AddsTags() { const string input = @"<div><a href=""http://blah.com/someurl"">Some URL</a><a>No href</a></div><div><a href=""http://blah.com/someurl?extra=1"">Extra Stuff</a><a href=""{{Handlebars}}"">Don't Touch</a></div>"; const string expected = @"<html><head></head><body><div><a href=""http://blah.com/someurl?utm_source=source&amp;utm_medium=medium&amp;utm_campaign=campaign&amp;utm_content=content"">Some URL</a><a>No href</a></div><div><a href=""http://blah.com/someurl?extra=1&amp;utm_source=source&amp;utm_medium=medium&amp;utm_campaign=campaign&amp;utm_content=content"">Extra Stuff</a><a href=""{{Handlebars}}"">Don't Touch</a></div></body></html>"; var premailedOutput = new PreMailer(input) .AddAnalyticsTags("source", "medium", "campaign", "content") .MoveCssInline(); Assert.True(expected == premailedOutput.Html); } [Fact] public void AddAnalyticsTags_AddsTagsAndExcludesDomain() { const string input = @"<div><a href=""http://www.blah.com/someurl"">Some URL</a><a>No href</a></div><div><a href=""https://www.nomatch.com/someurl?extra=1"">Extra Stuff</a><a href=""{{Handlebars}}"">Don't Touch</a></div>"; const string expected = @"<html><head></head><body><div><a href=""http://www.blah.com/someurl?utm_source=source&amp;utm_medium=medium&amp;utm_campaign=campaign&amp;utm_content=content"">Some URL</a><a>No href</a></div><div><a href=""https://www.nomatch.com/someurl?extra=1"">Extra Stuff</a><a href=""{{Handlebars}}"">Don't Touch</a></div></body></html>"; var premailedOutput = new PreMailer(input) .AddAnalyticsTags("source", "medium", "campaign", "content", "www.Blah.com") .MoveCssInline(); Assert.True(expected == premailedOutput.Html); } [Fact] public void AddAnalyticsTags_AddsTagsBeforeAnchorTags() { const string input = @"<div><a href=""https://github.com/premailer/premailer#premailer-specific-css"">Premailer Specific CSS</a></div>"; const string expected = @"<html><head></head><body><div><a href=""https://github.com/premailer/premailer?utm_source=source&amp;utm_medium=medium&amp;utm_campaign=campaign&amp;utm_content=content#premailer-specific-css"">Premailer Specific CSS</a></div></body></html>"; var premailedOutput = new PreMailer(input) .AddAnalyticsTags("source", "medium", "campaign", "content", "github.com") .MoveCssInline(); Assert.True(expected == premailedOutput.Html); } [Fact] public void ContainsLinkCssElement_DownloadsCss() { var mockDownloader = new Mock<IWebDownloader>(); mockDownloader.Setup(d => d.DownloadString(It.IsAny<Uri>())).Returns(".a { display: block; }"); WebDownloader.SharedDownloader = mockDownloader.Object; Uri baseUri = new Uri("http://a.com"); Uri fullUrl = new Uri(baseUri, "b.css"); string input = $"<html><head><link href=\"{fullUrl}\"></link></head><body><div id=\"high-imp\" class=\"test\">test</div></body></html>"; PreMailer sut = new PreMailer(input, baseUri); sut.MoveCssInline(); mockDownloader.Verify(d => d.DownloadString(fullUrl)); } [Fact] public void ContainsLinkCssElement_Bundle_DownloadsCss() { var mockDownloader = new Mock<IWebDownloader>(); mockDownloader.Setup(d => d.DownloadString(It.IsAny<Uri>())).Returns(".a { display: block; }"); WebDownloader.SharedDownloader = mockDownloader.Object; Uri baseUri = new Uri("http://a.com"); Uri fullUrl = new Uri(baseUri, "/Content/css?v=7V7TZzP9Wo7LiH9_q-r5mRBdC_N0lA_YJpRL_1V424E1"); string input = $"<html><head><link href=\"{fullUrl}\" rel=\"stylesheet\"></head><body><div id=\"high-imp\" class=\"test\">test</div></body></html>"; PreMailer sut = new PreMailer(input, baseUri); sut.MoveCssInline(); mockDownloader.Verify(d => d.DownloadString(fullUrl)); } [Fact] public void ContainsLinkCssElement_NotCssFile_DoNotDownload() { var mockDownloader = new Mock<IWebDownloader>(); mockDownloader.Setup(d => d.DownloadString(It.IsAny<Uri>())).Returns(".a { display: block; }"); WebDownloader.SharedDownloader = mockDownloader.Object; Uri baseUri = new Uri("http://a.com"); Uri fullUrl = new Uri(baseUri, "b.bs"); string input = $"<html><head><link href=\"{fullUrl}\"></link></head><body><div id=\"high-imp\" class=\"test\">test</div></body></html>"; PreMailer sut = new PreMailer(input, baseUri); sut.MoveCssInline(); mockDownloader.Verify(d => d.DownloadString(It.IsAny<Uri>()), Times.Never()); } [Fact] public void ContainsLinkCssElement_DownloadsCss_InlinesContent() { var mockDownloader = new Mock<IWebDownloader>(); mockDownloader.Setup(d => d.DownloadString(It.IsAny<Uri>())).Returns(".test { width: 150px; }"); WebDownloader.SharedDownloader = mockDownloader.Object; string input = "<html><head><link href=\"http://a.com/b.css\"></link></head><body><div class=\"test\">test</div></body></html>"; PreMailer sut = new PreMailer(input, new Uri("http://a.com")); var premailedOutput = sut.MoveCssInline(); Assert.Contains("<div class=\"test\" style=\"width: 150px\">", premailedOutput.Html); } [Fact] public void ContainsKeyframeCSS_InlinesCSSWithOutError() { string keyframeAnimation = @" @keyframes mymove { 0% {top: 0px;} 25% {top: 200px;} 75% {top: 50px} 100% {top: 100px;} } "; string input = "<html><head><style type=\"text/css\">.test { background-color:#f1f1f1; } " + keyframeAnimation + "</style></head><body><div class=\"test\">test</div></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.Contains("<div class=\"test\" style=\"background-color: #f1f1f1\"", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType() { string input = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_HTML5() { string docType = "<!DOCTYPE html>"; string input = $"{docType}<html><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html>", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_HTML401_Strict() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"; string input = $"{docType}<html><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html>", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_HTML401_Transitional() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; string input = $"{docType}<html><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html>", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_HTML401_Frameset() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">"; string input = $"{docType}<html><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html>", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_XHTML10_Strict() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; string input = $"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_XHTML10_Transitional() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; string input = $"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_XHTML10_Frameset() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">"; string input = $"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesDocType_XHTML11() { string docType = "<!DOCTYPE html PUBLIC \" -//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">"; string input = $"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith($"{docType}<html xmlns=\"http://www.w3.org/1999/xhtml\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_PreservesXMLNamespace() { string input = "<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\"><head></head><body></body></html>"; var premailedOutput = PreMailer.MoveCssInline(input, false); Assert.StartsWith("<html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\">", premailedOutput.Html); } [Fact] public void MoveCSSInline_MergingTwoValidCssRules() { string input = @"<html> <head> <style><!-- /* Font Definitions */ p.MsoNormal {margin:0cm;} p {mso-style-priority:99;} --></style> </head> <body> <div> <p class=""MsoNormal""><span style=""font-family:Source Sans Pro,serif"">Line1</span></p> </div> </body> </html>"; var premailedOutput = PreMailer.MoveCssInline(input, true, null, null); Assert.Contains("style=\"mso-style-priority: 99;margin: 0cm\"", premailedOutput.Html); } [Fact] public void MoveCSSInline_AcceptsStream() { string input = "<html><head><style type=\"text/css\" media=\"screen\">div { width: 100% }</style></head><body><div>Target</div></body></html>"; using (var stream = new MemoryStream()) { using (var writer = new StreamWriter(stream)) { writer.Write(input); writer.Flush(); stream.Position = 0; var premailedOutput = PreMailer.MoveCssInline(stream); Assert.Contains("<div style=\"width: 100%\">Target</div>", premailedOutput.Html); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using MarginTrading.Backend.Core; using MarginTrading.Backend.Core.Messages; namespace MarginTrading.Backend.Services { public class OrderCacheGroup { private readonly Dictionary<string, Order> _ordersById; private readonly Dictionary<string, HashSet<string>> _orderIdsByAccountId; private readonly Dictionary<string, HashSet<string>> _orderIdsByInstrumentId; private readonly Dictionary<(string, string), HashSet<string>> _orderIdsByAccountIdAndInstrumentId; private readonly Dictionary<string, HashSet<string>> _orderIdsByMarginInstrumentId; private readonly OrderStatus _status; private readonly ReaderWriterLockSlim _lockSlim = new ReaderWriterLockSlim(); public OrderCacheGroup(IReadOnlyCollection<Order> orders, OrderStatus status) { _status = status; var statusOrders = orders.Where(x => x.Status == status).ToList(); _lockSlim.EnterWriteLock(); try { _ordersById = statusOrders.ToDictionary(x => x.Id); _orderIdsByInstrumentId = statusOrders.GroupBy(x => x.Instrument) .ToDictionary(x => x.Key, x => x.Select(o => o.Id).ToHashSet()); _orderIdsByAccountId = statusOrders.GroupBy(x => x.AccountId) .ToDictionary(x => x.Key, x => x.Select(o => o.Id).ToHashSet()); _orderIdsByAccountIdAndInstrumentId = statusOrders.GroupBy(x => GetAccountInstrumentCacheKey(x.AccountId, x.Instrument)) .ToDictionary(x => x.Key, x => x.Select(o => o.Id).ToHashSet()); _orderIdsByMarginInstrumentId = statusOrders.Where(x => !string.IsNullOrEmpty(x.MarginCalcInstrument)) .GroupBy(x => x.MarginCalcInstrument) .ToDictionary(x => x.Key, x => x.Select(o => o.Id).ToHashSet()); } finally { _lockSlim.ExitWriteLock(); } } #region Setters public void Add(Order order) { _lockSlim.EnterWriteLock(); try { _ordersById.Add(order.Id, order); if (!_orderIdsByAccountId.ContainsKey(order.AccountId)) _orderIdsByAccountId.Add(order.AccountId, new HashSet<string>()); _orderIdsByAccountId[order.AccountId].Add(order.Id); if (!_orderIdsByInstrumentId.ContainsKey(order.Instrument)) _orderIdsByInstrumentId.Add(order.Instrument, new HashSet<string>()); _orderIdsByInstrumentId[order.Instrument].Add(order.Id); var accountInstrumentCacheKey = GetAccountInstrumentCacheKey(order.AccountId, order.Instrument); if (!_orderIdsByAccountIdAndInstrumentId.ContainsKey(accountInstrumentCacheKey)) _orderIdsByAccountIdAndInstrumentId.Add(accountInstrumentCacheKey, new HashSet<string>()); _orderIdsByAccountIdAndInstrumentId[accountInstrumentCacheKey].Add(order.Id); if (!string.IsNullOrEmpty(order.MarginCalcInstrument)) { if(!_orderIdsByMarginInstrumentId.ContainsKey(order.MarginCalcInstrument)) _orderIdsByMarginInstrumentId.Add(order.MarginCalcInstrument, new HashSet<string>()); _orderIdsByMarginInstrumentId[order.MarginCalcInstrument].Add(order.Id); } } finally { _lockSlim.ExitWriteLock(); } var account = MtServiceLocator.AccountsCacheService.Get(order.ClientId, order.AccountId); account.CacheNeedsToBeUpdated(); } public void Remove(Order order) { _lockSlim.EnterWriteLock(); try { if (_ordersById.Remove(order.Id)) { _orderIdsByInstrumentId[order.Instrument].Remove(order.Id); _orderIdsByAccountId[order.AccountId].Remove(order.Id); _orderIdsByAccountIdAndInstrumentId[GetAccountInstrumentCacheKey(order.AccountId, order.Instrument)].Remove(order.Id); if (!string.IsNullOrEmpty(order.MarginCalcInstrument) && (_orderIdsByMarginInstrumentId[order.MarginCalcInstrument]?.Contains(order.Id) ?? false)) _orderIdsByMarginInstrumentId[order.MarginCalcInstrument].Remove(order.Id); } else throw new Exception(string.Format(MtMessages.CantRemoveOrderWithStatus, order.Id, _status)); } finally { _lockSlim.ExitWriteLock(); } var account = MtServiceLocator.AccountsCacheService?.Get(order.ClientId, order.AccountId); account?.CacheNeedsToBeUpdated(); } #endregion #region Getters public Order GetOrderById(string orderId) { if (TryGetOrderById(orderId, out var result)) return result; throw new Exception(string.Format(MtMessages.CantGetOrderWithStatus, orderId, _status)); } public bool TryGetOrderById(string orderId, out Order result) { _lockSlim.EnterReadLock(); try { if (!_ordersById.ContainsKey(orderId)) { result = null; return false; } result = _ordersById[orderId]; return true; } finally { _lockSlim.ExitReadLock(); } } public IReadOnlyCollection<Order> GetOrdersByInstrument(string instrument) { if (string.IsNullOrWhiteSpace(instrument)) throw new ArgumentException(nameof(instrument)); _lockSlim.EnterReadLock(); try { if (!_orderIdsByInstrumentId.ContainsKey(instrument)) return new List<Order>(); return _orderIdsByInstrumentId[instrument].Select(id => _ordersById[id]).ToList(); } finally { _lockSlim.ExitReadLock(); } } public IReadOnlyCollection<Order> GetOrdersByMarginInstrument(string instrument) { if (string.IsNullOrWhiteSpace(instrument)) throw new ArgumentException(nameof(instrument)); _lockSlim.EnterReadLock(); try { if (!_orderIdsByMarginInstrumentId.ContainsKey(instrument)) return new List<Order>(); return _orderIdsByMarginInstrumentId[instrument].Select(id => _ordersById[id]).ToList(); } finally { _lockSlim.ExitReadLock(); } } public ICollection<Order> GetOrdersByInstrumentAndAccount(string instrument, string accountId) { if (string.IsNullOrWhiteSpace(instrument)) throw new ArgumentException(nameof(instrument)); if (string.IsNullOrWhiteSpace(accountId)) throw new ArgumentException(nameof(instrument)); var key = GetAccountInstrumentCacheKey(accountId, instrument); _lockSlim.EnterReadLock(); try { if (!_orderIdsByAccountIdAndInstrumentId.ContainsKey(key)) return new List<Order>(); return _orderIdsByAccountIdAndInstrumentId[key].Select(id => _ordersById[id]).ToList(); } finally { _lockSlim.ExitReadLock(); } } public IReadOnlyCollection<Order> GetAllOrders() { _lockSlim.EnterReadLock(); try { return _ordersById.Values; } finally { _lockSlim.ExitReadLock(); } } public ICollection<Order> GetOrdersByAccountIds(params string[] accountIds) { _lockSlim.EnterReadLock(); var result = new List<Order>(); try { foreach (var accountId in accountIds) { if (!_orderIdsByAccountId.ContainsKey(accountId)) continue; foreach (var orderId in _orderIdsByAccountId[accountId]) result.Add(_ordersById[orderId]); } return result; } finally { _lockSlim.ExitReadLock(); } } #endregion #region Helpers private (string, string) GetAccountInstrumentCacheKey(string accountId, string instrumentId) { return (accountId, instrumentId); } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using System; using System.IO; using NPOI.HSSF.UserModel; using NPOI.OpenXml4Net.OPC; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.XSSF.UserModel; namespace NPOI.SS.UserModel { public enum ImportOption { NONE, /// <summary> /// Only Text and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> SheetContentOnly, /// <summary> /// Only Text, Comments and Formulas are imported. Pictures, Drawing, Styles etc. are all ignored. /// </summary> TextOnly, /// <summary> /// Everything is imported - this is the same as NONE. /// </summary> All, } /// <summary> /// Factory for creating the appropriate kind of Workbook /// (be it HSSFWorkbook or XSSFWorkbook), from the given input /// </summary> public class WorkbookFactory { /// <summary> /// Creates an HSSFWorkbook from the given POIFSFileSystem /// </summary> public static IWorkbook Create(POIFSFileSystem fs) { return new HSSFWorkbook(fs); } /** * Creates an HSSFWorkbook from the given NPOIFSFileSystem */ public static IWorkbook Create(NPOIFSFileSystem fs) { return new HSSFWorkbook(fs.Root, true); } /// <summary> /// Creates an XSSFWorkbook from the given OOXML Package /// </summary> public static IWorkbook Create(OPCPackage pkg) { return new XSSFWorkbook(pkg); } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> // Your input stream MUST either support mark/reset, or // be wrapped as a {@link PushbackInputStream}! public static IWorkbook Create(Stream inputStream) { // If Clearly doesn't do mark/reset, wrap up //if (!inp.MarkSupported()) //{ // inp = new PushbackInputStream(inp, 8); //} inputStream = new PushbackStream(inputStream); if (POIFSFileSystem.HasPOIFSHeader(inputStream)) { return new HSSFWorkbook(inputStream); } inputStream.Position = 0; if (POIXMLDocument.HasOOXMLHeader(inputStream)) { return new XSSFWorkbook(OPCPackage.Open(inputStream)); } throw new ArgumentException("Your stream was neither an OLE2 stream, nor an OOXML stream."); } /** * Creates the appropriate HSSFWorkbook / XSSFWorkbook from * the given File, which must exist and be readable. * <p>Note that for Workbooks opened this way, it is not possible * to explicitly close the underlying File resource. */ public static IWorkbook Create(string file) { if (!File.Exists(file)) { throw new FileNotFoundException(file); } //FileStream fStream = null; try { //using (fStream = new FileStream(file, FileMode.Open, FileAccess.Read)) //{ // IWorkbook wb = new HSSFWorkbook(fStream); // return wb; //} NPOIFSFileSystem fs = new NPOIFSFileSystem(new FileInfo(file), true); return new HSSFWorkbook(fs.Root, true); } catch (OfficeXmlFileException e) { // opening as .xls failed => try opening as .xlsx OPCPackage pkg = OPCPackage.Open(file); try { return new XSSFWorkbook(pkg); } catch (IOException ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } catch (ArgumentException ioe) { // ensure that file handles are closed (use revert() to not re-write the file) pkg.Revert(); //pkg.close(); // rethrow exception throw ioe; } } } /// <summary> /// Creates the appropriate HSSFWorkbook / XSSFWorkbook from /// the given InputStream. The Stream is wraped inside a PushbackInputStream. /// </summary> /// <param name="inputStream">Input Stream of .xls or .xlsx file</param> /// <param name="importOption">Customize the elements that are processed on the next import</param> /// <returns>IWorkbook depending on the input HSSFWorkbook or XSSFWorkbook is returned.</returns> public static IWorkbook Create(Stream inputStream, ImportOption importOption) { SetImportOption(importOption); IWorkbook workbook = Create(inputStream); return workbook; } /// <summary> /// Creates a specific FormulaEvaluator for the given workbook. /// </summary> public static IFormulaEvaluator CreateFormulaEvaluator(IWorkbook workbook) { if (typeof(HSSFWorkbook) == workbook.GetType()) { return new HSSFFormulaEvaluator(workbook as HSSFWorkbook); } else { return new XSSFFormulaEvaluator(workbook as XSSFWorkbook); } } /// <summary> /// Sets the import option when opening the next workbook. /// Works only for XSSF. For HSSF workbooks this option is ignored. /// </summary> /// <param name="importOption">Customize the elements that are processed on the next import</param> public static void SetImportOption(ImportOption importOption) { if (ImportOption.SheetContentOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else if (ImportOption.TextOnly == importOption) { // Add XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); // Remove XSSFRelation.RemoveRelation(XSSFRelation.WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.RemoveRelation(XSSFRelation.CHARTSHEET); XSSFRelation.RemoveRelation(XSSFRelation.STYLES); XSSFRelation.RemoveRelation(XSSFRelation.DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CHART); XSSFRelation.RemoveRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.RemoveRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.RemoveRelation(XSSFRelation.TABLE); XSSFRelation.RemoveRelation(XSSFRelation.IMAGES); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.RemoveRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.RemoveRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.RemoveRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.RemoveRelation(XSSFRelation.VBA_MACROS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.RemoveRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.RemoveRelation(XSSFRelation.THEME); XSSFRelation.RemoveRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.RemoveRelation(XSSFRelation.PRINTER_SETTINGS); } else { // NONE/All XSSFRelation.AddRelation(XSSFRelation.WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACROS_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_TEMPLATE_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.MACRO_ADDIN_WORKBOOK); XSSFRelation.AddRelation(XSSFRelation.WORKSHEET); XSSFRelation.AddRelation(XSSFRelation.CHARTSHEET); XSSFRelation.AddRelation(XSSFRelation.SHARED_STRINGS); XSSFRelation.AddRelation(XSSFRelation.STYLES); XSSFRelation.AddRelation(XSSFRelation.DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CHART); XSSFRelation.AddRelation(XSSFRelation.VML_DRAWINGS); XSSFRelation.AddRelation(XSSFRelation.CUSTOM_XML_MAPPINGS); XSSFRelation.AddRelation(XSSFRelation.TABLE); XSSFRelation.AddRelation(XSSFRelation.IMAGES); XSSFRelation.AddRelation(XSSFRelation.IMAGE_EMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_WMF); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PICT); XSSFRelation.AddRelation(XSSFRelation.IMAGE_JPEG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_PNG); XSSFRelation.AddRelation(XSSFRelation.IMAGE_DIB); XSSFRelation.AddRelation(XSSFRelation.SHEET_COMMENTS); XSSFRelation.AddRelation(XSSFRelation.SHEET_HYPERLINKS); XSSFRelation.AddRelation(XSSFRelation.OLEEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.PACKEMBEDDINGS); XSSFRelation.AddRelation(XSSFRelation.VBA_MACROS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_CONTROLS); XSSFRelation.AddRelation(XSSFRelation.ACTIVEX_BINS); XSSFRelation.AddRelation(XSSFRelation.THEME); XSSFRelation.AddRelation(XSSFRelation.CALC_CHAIN); XSSFRelation.AddRelation(XSSFRelation.PRINTER_SETTINGS); } } } }
// 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.Azure.AcceptanceTestsAzureReport { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Test Infrastructure for AutoRest /// </summary> public partial class AutoRestReportServiceForAzure : Microsoft.Rest.ServiceClient<AutoRestReportServiceForAzure>, IAutoRestReportServiceForAzure, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzure(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestReportServiceForAzure(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzure(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestReportServiceForAzure(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestReportServiceForAzure class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestReportServiceForAzure(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } /// <summary> /// Get test coverage report /// </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="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetReportWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetReport", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "report/azure").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<System.Collections.Generic.IDictionary<string, int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IDictionary<string, int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Media; using Nop.Services.Localization; using Nop.Services.Media; using Nop.Services.Seo; using Nop.Services.Stores; namespace Nop.Services.Catalog { /// <summary> /// Copy Product service /// </summary> public partial class CopyProductService : ICopyProductService { #region Fields private readonly IProductService _productService; private readonly IProductAttributeService _productAttributeService; private readonly ILanguageService _languageService; private readonly ILocalizedEntityService _localizedEntityService; private readonly IPictureService _pictureService; private readonly ICategoryService _categoryService; private readonly IManufacturerService _manufacturerService; private readonly ISpecificationAttributeService _specificationAttributeService; private readonly IDownloadService _downloadService; private readonly IProductAttributeParser _productAttributeParser; private readonly IProductTagService _productTagService; private readonly IUrlRecordService _urlRecordService; private readonly IStoreMappingService _storeMappingService; #endregion #region Ctor public CopyProductService(IProductService productService, IProductAttributeService productAttributeService, ILanguageService languageService, ILocalizedEntityService localizedEntityService, IPictureService pictureService, ICategoryService categoryService, IManufacturerService manufacturerService, ISpecificationAttributeService specificationAttributeService, IDownloadService downloadService, IProductAttributeParser productAttributeParser, IProductTagService productTagService, IUrlRecordService urlRecordService, IStoreMappingService storeMappingService) { this._productService = productService; this._productAttributeService = productAttributeService; this._languageService = languageService; this._localizedEntityService = localizedEntityService; this._pictureService = pictureService; this._categoryService = categoryService; this._manufacturerService = manufacturerService; this._specificationAttributeService = specificationAttributeService; this._downloadService = downloadService; this._productAttributeParser = productAttributeParser; this._productTagService = productTagService; this._urlRecordService = urlRecordService; this._storeMappingService = storeMappingService; } #endregion #region Methods /// <summary> /// Create a copy of product with all depended data /// </summary> /// <param name="product">The product to copy</param> /// <param name="newName">The name of product duplicate</param> /// <param name="isPublished">A value indicating whether the product duplicate should be published</param> /// <param name="copyImages">A value indicating whether the product images should be copied</param> /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param> /// <returns>Product copy</returns> public virtual Product CopyProduct(Product product, string newName, bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true) { if (product == null) throw new ArgumentNullException("product"); if (String.IsNullOrEmpty(newName)) throw new ArgumentException("Product name is required"); Product productCopy = null; //product download & sample download int downloadId = product.DownloadId; int sampleDownloadId = product.SampleDownloadId; if (product.IsDownload) { var download = _downloadService.GetDownloadById(product.DownloadId); if (download != null) { var downloadCopy = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = download.UseDownloadUrl, DownloadUrl = download.DownloadUrl, DownloadBinary = download.DownloadBinary, ContentType = download.ContentType, Filename = download.Filename, Extension = download.Extension, IsNew = download.IsNew, }; _downloadService.InsertDownload(downloadCopy); downloadId = downloadCopy.Id; } if (product.HasSampleDownload) { var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId); if (sampleDownload != null) { var sampleDownloadCopy = new Download() { DownloadGuid = Guid.NewGuid(), UseDownloadUrl = sampleDownload.UseDownloadUrl, DownloadUrl = sampleDownload.DownloadUrl, DownloadBinary = sampleDownload.DownloadBinary, ContentType = sampleDownload.ContentType, Filename = sampleDownload.Filename, Extension = sampleDownload.Extension, IsNew = sampleDownload.IsNew }; _downloadService.InsertDownload(sampleDownloadCopy); sampleDownloadId = sampleDownloadCopy.Id; } } } // product productCopy = new Product() { ProductTypeId = product.ProductTypeId, ParentGroupedProductId = product.ParentGroupedProductId, VisibleIndividually = product.VisibleIndividually, Name = newName, ShortDescription = product.ShortDescription, FullDescription = product.FullDescription, VendorId = product.VendorId, ProductTemplateId = product.ProductTemplateId, AdminComment = product.AdminComment, ShowOnHomePage = product.ShowOnHomePage, MetaKeywords = product.MetaKeywords, MetaDescription = product.MetaDescription, MetaTitle = product.MetaTitle, AllowCustomerReviews = product.AllowCustomerReviews, LimitedToStores = product.LimitedToStores, Sku = product.Sku, ManufacturerPartNumber = product.ManufacturerPartNumber, Gtin = product.Gtin, IsGiftCard = product.IsGiftCard, GiftCardType = product.GiftCardType, RequireOtherProducts = product.RequireOtherProducts, RequiredProductIds = product.RequiredProductIds, AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts, IsDownload = product.IsDownload, DownloadId = downloadId, UnlimitedDownloads = product.UnlimitedDownloads, MaxNumberOfDownloads = product.MaxNumberOfDownloads, DownloadExpirationDays = product.DownloadExpirationDays, DownloadActivationType = product.DownloadActivationType, HasSampleDownload = product.HasSampleDownload, SampleDownloadId = sampleDownloadId, HasUserAgreement = product.HasUserAgreement, UserAgreementText = product.UserAgreementText, IsRecurring = product.IsRecurring, RecurringCycleLength = product.RecurringCycleLength, RecurringCyclePeriod = product.RecurringCyclePeriod, RecurringTotalCycles = product.RecurringTotalCycles, IsShipEnabled = product.IsShipEnabled, IsFreeShipping = product.IsFreeShipping, AdditionalShippingCharge = product.AdditionalShippingCharge, DeliveryDateId = product.DeliveryDateId, WarehouseId = product.WarehouseId, IsTaxExempt = product.IsTaxExempt, TaxCategoryId = product.TaxCategoryId, ManageInventoryMethod = product.ManageInventoryMethod, StockQuantity = product.StockQuantity, DisplayStockAvailability = product.DisplayStockAvailability, DisplayStockQuantity = product.DisplayStockQuantity, MinStockQuantity = product.MinStockQuantity, LowStockActivityId = product.LowStockActivityId, NotifyAdminForQuantityBelow = product.NotifyAdminForQuantityBelow, BackorderMode = product.BackorderMode, AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions, OrderMinimumQuantity = product.OrderMinimumQuantity, OrderMaximumQuantity = product.OrderMaximumQuantity, AllowedQuantities = product.AllowedQuantities, AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations, DisableBuyButton = product.DisableBuyButton, DisableWishlistButton = product.DisableWishlistButton, AvailableForPreOrder = product.AvailableForPreOrder, PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc, CallForPrice = product.CallForPrice, Price = product.Price, OldPrice = product.OldPrice, ProductCost = product.ProductCost, SpecialPrice = product.SpecialPrice, SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc, SpecialPriceEndDateTimeUtc = product.SpecialPriceEndDateTimeUtc, CustomerEntersPrice = product.CustomerEntersPrice, MinimumCustomerEnteredPrice = product.MinimumCustomerEnteredPrice, MaximumCustomerEnteredPrice = product.MaximumCustomerEnteredPrice, Weight = product.Weight, Length = product.Length, Width = product.Width, Height = product.Height, AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc, AvailableEndDateTimeUtc = product.AvailableEndDateTimeUtc, DisplayOrder = product.DisplayOrder, Published = isPublished, Deleted = product.Deleted, CreatedOnUtc = DateTime.UtcNow, UpdatedOnUtc = DateTime.UtcNow }; //validate search engine name _productService.InsertProduct(productCopy); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0); var languages = _languageService.GetAllLanguages(true); //localization foreach (var lang in languages) { var name = product.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id); var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(shortDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id); var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(fullDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id); var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false); if (!String.IsNullOrEmpty(metaKeywords)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id); var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false); if (!String.IsNullOrEmpty(metaDescription)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id); var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false); if (!String.IsNullOrEmpty(metaTitle)) _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id); //search engine name _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id); } //product tags foreach (var productTag in product.ProductTags) { productCopy.ProductTags.Add(productTag); } _productService.UpdateProduct(product); // product pictures //variant to store original and new picture identifiers var originalNewPictureIdentifiers = new Dictionary<int, int>(); if (copyImages) { foreach (var productPicture in product.ProductPictures) { var picture = productPicture.Picture; var pictureCopy = _pictureService.InsertPicture( _pictureService.LoadPictureBinary(picture), picture.MimeType, _pictureService.GetPictureSeName(newName), true); _productService.InsertProductPicture(new ProductPicture() { ProductId = productCopy.Id, PictureId = pictureCopy.Id, DisplayOrder = productPicture.DisplayOrder }); originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id); } } // product <-> categories mappings foreach (var productCategory in product.ProductCategories) { var productCategoryCopy = new ProductCategory() { ProductId = productCopy.Id, CategoryId = productCategory.CategoryId, IsFeaturedProduct = productCategory.IsFeaturedProduct, DisplayOrder = productCategory.DisplayOrder }; _categoryService.InsertProductCategory(productCategoryCopy); } // product <-> manufacturers mappings foreach (var productManufacturers in product.ProductManufacturers) { var productManufacturerCopy = new ProductManufacturer() { ProductId = productCopy.Id, ManufacturerId = productManufacturers.ManufacturerId, IsFeaturedProduct = productManufacturers.IsFeaturedProduct, DisplayOrder = productManufacturers.DisplayOrder }; _manufacturerService.InsertProductManufacturer(productManufacturerCopy); } // product <-> releated products mappings foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true)) { _productService.InsertRelatedProduct( new RelatedProduct() { ProductId1 = productCopy.Id, ProductId2 = relatedProduct.ProductId2, DisplayOrder = relatedProduct.DisplayOrder }); } // product <-> cross sells mappings foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true)) { _productService.InsertCrossSellProduct( new CrossSellProduct() { ProductId1 = productCopy.Id, ProductId2 = csProduct.ProductId2, }); } // product specifications foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes) { var psaCopy = new ProductSpecificationAttribute() { ProductId = productCopy.Id, SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId, CustomValue = productSpecificationAttribute.CustomValue, AllowFiltering = productSpecificationAttribute.AllowFiltering, ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage, DisplayOrder = productSpecificationAttribute.DisplayOrder }; _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy); } //store mapping var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product); foreach (var id in selectedStoreIds) { _storeMappingService.InsertStoreMapping(productCopy, id); } // product <-> attributes mappings var associatedAttributes = new Dictionary<int, int>(); var associatedAttributeValues = new Dictionary<int, int>(); foreach (var productVariantAttribute in _productAttributeService.GetProductVariantAttributesByProductId(product.Id)) { var productVariantAttributeCopy = new ProductVariantAttribute() { ProductId = productCopy.Id, ProductAttributeId = productVariantAttribute.ProductAttributeId, TextPrompt = productVariantAttribute.TextPrompt, IsRequired = productVariantAttribute.IsRequired, AttributeControlTypeId = productVariantAttribute.AttributeControlTypeId, DisplayOrder = productVariantAttribute.DisplayOrder, ValidationMinLength = productVariantAttribute.ValidationMinLength, ValidationMaxLength = productVariantAttribute.ValidationMaxLength, ValidationFileAllowedExtensions = productVariantAttribute.ValidationFileAllowedExtensions, ValidationFileMaximumSize = productVariantAttribute.ValidationFileMaximumSize, DefaultValue = productVariantAttribute.DefaultValue, }; _productAttributeService.InsertProductVariantAttribute(productVariantAttributeCopy); //save associated value (used for combinations copying) associatedAttributes.Add(productVariantAttribute.Id, productVariantAttributeCopy.Id); // product variant attribute values var productVariantAttributeValues = _productAttributeService.GetProductVariantAttributeValues(productVariantAttribute.Id); foreach (var productVariantAttributeValue in productVariantAttributeValues) { int pvavPictureId = 0; if (originalNewPictureIdentifiers.ContainsKey(productVariantAttributeValue.PictureId)) { pvavPictureId = originalNewPictureIdentifiers[productVariantAttributeValue.PictureId]; } var pvavCopy = new ProductVariantAttributeValue() { ProductVariantAttributeId = productVariantAttributeCopy.Id, AttributeValueTypeId = productVariantAttributeValue.AttributeValueTypeId, AssociatedProductId = productVariantAttributeValue.AssociatedProductId, Name = productVariantAttributeValue.Name, ColorSquaresRgb = productVariantAttributeValue.ColorSquaresRgb, PriceAdjustment = productVariantAttributeValue.PriceAdjustment, WeightAdjustment = productVariantAttributeValue.WeightAdjustment, Cost = productVariantAttributeValue.Cost, Quantity = productVariantAttributeValue.Quantity, IsPreSelected = productVariantAttributeValue.IsPreSelected, DisplayOrder = productVariantAttributeValue.DisplayOrder, PictureId = pvavPictureId, }; _productAttributeService.InsertProductVariantAttributeValue(pvavCopy); //save associated value (used for combinations copying) associatedAttributeValues.Add(productVariantAttributeValue.Id, pvavCopy.Id); //localization foreach (var lang in languages) { var name = productVariantAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false); if (!String.IsNullOrEmpty(name)) _localizedEntityService.SaveLocalizedValue(pvavCopy, x => x.Name, name, lang.Id); } } } //attribute combinations foreach (var combination in _productAttributeService.GetAllProductVariantAttributeCombinations(product.Id)) { //generate new AttributesXml according to new value IDs string newAttributesXml = ""; var parsedProductVariantAttributes = _productAttributeParser.ParseProductVariantAttributes(combination.AttributesXml); foreach (var oldPva in parsedProductVariantAttributes) { if (associatedAttributes.ContainsKey(oldPva.Id)) { int newPvaId = associatedAttributes[oldPva.Id]; var newPva = _productAttributeService.GetProductVariantAttributeById(newPvaId); if (newPva != null) { var oldPvaValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldPva.Id); foreach (var oldPvaValueStr in oldPvaValuesStr) { if (newPva.ShouldHaveValues()) { //attribute values int oldPvaValue = int.Parse(oldPvaValueStr); if (associatedAttributeValues.ContainsKey(oldPvaValue)) { int newPvavId = associatedAttributeValues[oldPvaValue]; var newPvav = _productAttributeService.GetProductVariantAttributeValueById(newPvavId); if (newPvav != null) { newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, newPvav.Id.ToString()); } } } else { //just a text newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml, newPva, oldPvaValueStr); } } } } } var combinationCopy = new ProductVariantAttributeCombination() { ProductId = productCopy.Id, AttributesXml = newAttributesXml, StockQuantity = combination.StockQuantity, AllowOutOfStockOrders = combination.AllowOutOfStockOrders, Sku = combination.Sku, ManufacturerPartNumber = combination.ManufacturerPartNumber, Gtin = combination.Gtin, OverriddenPrice = combination.OverriddenPrice }; _productAttributeService.InsertProductVariantAttributeCombination(combinationCopy); } //tier prices foreach (var tierPrice in product.TierPrices) { _productService.InsertTierPrice( new TierPrice() { ProductId = productCopy.Id, StoreId = tierPrice.StoreId, CustomerRoleId = tierPrice.CustomerRoleId, Quantity = tierPrice.Quantity, Price = tierPrice.Price }); } // product <-> discounts mapping foreach (var discount in product.AppliedDiscounts) { productCopy.AppliedDiscounts.Add(discount); _productService.UpdateProduct(productCopy); } //update "HasTierPrices" and "HasDiscountsApplied" properties _productService.UpdateHasTierPricesProperty(productCopy); _productService.UpdateHasDiscountsApplied(productCopy); //associated products if (copyAssociatedProducts) { var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true); foreach (var associatedProduct in associatedProducts) { var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name), isPublished, copyImages, false); associatedProductCopy.ParentGroupedProductId = productCopy.Id; _productService.UpdateProduct(productCopy); } } return productCopy; } #endregion } }
using System; using System.Collections.Generic; namespace Tree4 { public struct T4_rect { public double Xmin; public double Xmax; public double Ymin; public double Ymax; public double W { get { return Xmax - Xmin; } } public double H { get { return Ymax - Ymin; } } public double Xc { get { return (Xmax + Xmin) / 2; } } public double Yc { get { return (Ymax + Ymin) / 2; } } public double Max_squared_distance_to_pt(double x, double y) { double dx0 = (Xmin - x); double dx1 = (Xmax - x); double dy0 = (Ymin - y); double dy1 = (Ymax - y); double d0 = (dx0 * dx0) + (dy0 * dy0); double d1 = (dx1 * dx1) + (dy0 * dy0); double d2 = (dx0 * dx0) + (dy1 * dy1); double d3 = (dx1 * dx1) + (dy1 * dy1); return Math.Max(Math.Max(Math.Max(d0, d1), d2), d3); } public double Min_squared_outside_distance_to_pt(double x, double y) { double dx = 0; double dy = 0; if (x < Xmin) dx = Xmin - x; else if (x > Xmax) dx = x - Xmax; if (y < Ymin) dy = Ymin - y; else if (y > Ymax) dy = y - Ymax; //NOTE: will return 0 for the point inside rect return (dx * dx) + (dy * dy); } public double Max_distance_to_pt(double x, double y) { return Math.Sqrt(Max_squared_distance_to_pt(x, y)); } public double Min_outside_distance_to_pt(double x, double y) { return Math.Sqrt(Min_squared_outside_distance_to_pt(x, y)); } // maybe it's wrong. gotta check public bool Is_intersects_with(T4_rect he) { if (this.Xmax < he.Xmin) return false; if (this.Xmin > he.Xmax) return false; if (this.Ymax < he.Ymin) return false; if (this.Ymin > he.Ymax) return false; return true; } public T4_rect(double xmin, double ymin, double xmax, double ymax) { this.Xmin = xmin; this.Xmax = xmax; this.Ymin = ymin; this.Ymax = ymax; } } public class T4 { private struct T4_occupant { public T4_rect Rect; public object Obj; public T4_occupant(T4_rect rect, object obj) { this.Rect = rect; this.Obj = obj; } } private const int MAX_OCCUPANTS = 8; private T4[] _rooms; private T4_rect _rect; private List<T4_occupant> _occupants = new List<T4_occupant>(); public T4_rect Rect { get { return _rect; }} private void split() { double mid_x = _rect.Xc; double mid_y = _rect.Yc; _rooms = new T4[4]; // quads ordering is ccw: // 0) left bottom // 1) right bottom // 2) right top // 3) left top _rooms[0] = new T4(new T4_rect(_rect.Xmin, _rect.Ymin, _rect.Xc, _rect.Yc)); _rooms[1] = new T4(new T4_rect(_rect.Xc, _rect.Ymin, _rect.Xmax, _rect.Yc)); _rooms[2] = new T4(new T4_rect(_rect.Xc, _rect.Yc, _rect.Xmax, _rect.Ymax)); _rooms[3] = new T4(new T4_rect(_rect.Xmin, _rect.Yc, _rect.Xc, _rect.Ymax)); } private int choose_room(T4_occupant occupant) { bool is_bottom_quads = occupant.Rect.Ymin > _rect.Ymin && occupant.Rect.Ymax < _rect.Yc; bool is_top_quads = occupant.Rect.Ymin > _rect.Yc && occupant.Rect.Ymax < _rect.Ymax; bool is_left_quads = occupant.Rect.Xmin > _rect.Xmin && occupant.Rect.Xmax < _rect.Xc; bool is_right_quads = occupant.Rect.Xmin > _rect.Xc && occupant.Rect.Xmax < _rect.Xmax; if (! (is_top_quads ^ is_bottom_quads)) return -1; if (! (is_left_quads ^ is_right_quads)) return -1; if (is_bottom_quads) return is_left_quads ? 0 : 1; return is_right_quads ? 2 : 3; } private void relocate() { if (_rooms == null) split(); // try to relocate occupants to the smaller rooms for (int i = _occupants.Count - 1; i >= 0; i--) { T4_occupant occupant = _occupants[i]; int idx = choose_room(occupant); if (idx < 0) continue; // occupant is too large _occupants.RemoveAt(i); _rooms[idx].add(occupant); } } private void add(T4_occupant occupant) { if (_rooms != null) { int idx = choose_room(occupant); // choosed a room for occupant successfully if (idx != -1) { _rooms[idx].add(occupant); return; } } _occupants.Add(occupant); if (_occupants.Count > MAX_OCCUPANTS) relocate(); } private List<T4_occupant> get_internal_occupants(double x, double y, ref double max_squared_dist) { List<T4_occupant> result = new List<T4_occupant>(); if (_rooms != null) { // if there is a rooms, there are some objects. // so we may safely trim max distance by own dimensions double max_own_dist = _rect.Max_squared_distance_to_pt(x, y); if (max_own_dist < max_squared_dist) max_squared_dist = max_own_dist; // sort rooms by minimum distance and visit 'em int[] room_idxes = new int[] { 0, 1, 2, 3 }; double[] room_distances = new double[] { _rooms[0]._rect.Min_squared_outside_distance_to_pt(x, y), _rooms[1]._rect.Min_squared_outside_distance_to_pt(x, y), _rooms[2]._rect.Min_squared_outside_distance_to_pt(x, y), _rooms[3]._rect.Min_squared_outside_distance_to_pt(x, y), }; Array.Sort(room_distances, room_idxes); // if max distance bound changed while visiting, some rooms would be skipped for (int i = 0; i < 4; i++) { if (room_distances[i] <= max_squared_dist) result.AddRange(_rooms[room_idxes[i]].get_internal_occupants(x, y, ref max_squared_dist)); } } // if there are some objects inside the room, check distance to them foreach (T4_occupant occupant in _occupants) { double min = occupant.Rect.Min_squared_outside_distance_to_pt(x, y); if (min > max_squared_dist) continue; // not in touch result.Add(occupant); double max = occupant.Rect.Max_squared_distance_to_pt(x, y); if (max < max_squared_dist) max_squared_dist = max; } return result; } private List<T4_occupant> get_nearest_occupants(double x, double y) { double max_squared_dist = _rect.H * _rect.H + _rect.W * _rect.W; List<T4_occupant> occupants = get_internal_occupants(x, y, ref max_squared_dist); // shouldn't happen for non-empty regions and pickpoint inside if (occupants.Count == 0) return occupants; // purge outdated candidates (collected before dist refinement) // find nearest occupant. all chances nearest occupant would be the last added // because it trims the max dist most // remove all occupants starting after the end of the nearest T4_occupant nearest = occupants[occupants.Count - 1]; double nearest_end = nearest.Rect.Max_squared_distance_to_pt(x, y); for (int i = occupants.Count - 2; i >= 0; i--) { if (occupants[i].Rect.Min_squared_outside_distance_to_pt(x, y) > nearest_end) occupants.RemoveAt(i); } return occupants; } private List<T4_occupant> get_colliders(T4_rect checkbox) { List<T4_occupant> colliders = new List<T4_occupant>(); // nothing to look here and deeper, we're outside of rect if (! _rect.Is_intersects_with(checkbox)) return colliders; // add occupants from the deeper rooms if (_rooms != null) { foreach (T4 room in _rooms) colliders.AddRange(room.get_colliders(checkbox)); } // add own occupants foreach (T4_occupant occupant in _occupants) { if (occupant.Rect.Is_intersects_with(checkbox)) colliders.Add(occupant); } return colliders; } public void Add(T4_rect rect, object obj) { add(new T4_occupant(rect, obj)); } public List<T4_rect> Traverse_rects() { List<T4_rect> result = new List<T4_rect>(); result.Add(_rect); if (_rooms != null) { foreach (T4 room in _rooms) { result.AddRange(room.Traverse_rects()); } } return result; } public List<object> Get_nearest_objects(double x, double y) { List<object> objects = new List<object>(); foreach (T4_occupant occupant in get_nearest_occupants(x, y)) objects.Add(occupant.Obj); return objects; } public List<T4_rect> Get_nearest_obj_rects(double x, double y) { List<T4_rect> rects = new List<T4_rect>(); foreach (T4_occupant occupant in get_nearest_occupants(x, y)) rects.Add(occupant.Rect); return rects; } public List<object> Get_colliding_objects(T4_rect checkbox) { List<object> objects = new List<object>(); foreach (T4_occupant occupant in get_colliders(checkbox)) objects.Add(occupant.Obj); return objects; } public List<T> Get_colliding_objects<T>(T4_rect checkbox) { List<T> objects = new List<T>(); foreach (T4_occupant occupant in get_colliders(checkbox)) objects.Add((T)occupant.Obj); return objects; } public List<T4_rect> Get_colliding_obj_rects(T4_rect checkbox) { List<T4_rect> rects = new List<T4_rect>(); foreach (T4_occupant occupant in get_colliders(checkbox)) rects.Add(occupant.Rect); return rects; } public T4(T4_rect rect) { _rect = rect; } } }
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using Intellisense.Common; using RoslynIntellisense; using Microsoft.CodeAnalysis; using System.Threading; namespace Syntaxer { class SyntaxProvider { static public string ProcessRequest(Args args) { try { if (args.script.HasText() && Path.GetExtension(args.script).ToLower() == ".vb") Autocompleter.Language = "VB"; if (args.popen.HasText()) { string[] parts = args.popen.Split('|').ToArray(); string exe = parts.FirstOrDefault(); if (parts.Count() == 2) Process.Start(parts.First(), parts.Last()); else if (parts.Count() == 1) Process.Start(parts.First()); else return "<error>Invalid 'popen' arguments. Must be <exe>[|<args>]"; return null; } if (args.pkill) { PKill(args.pid, args.pname); return null; } if (args.cscs_path != null) { if (csscript.cscs_path != args.cscs_path) { csscript.cscs_path = Path.GetFullPath(args.cscs_path); Output.WriteLine(" >> cscs.exe is remapped to: " + csscript.cscs_path); } return null; } if (args.op == "ping") { try { Autocompleter.Load(); return "ready"; } catch { return "not ready"; } } if (!File.Exists(args.script)) if (args.script.HasText()) return $"<error>File '{args.script}' doesn't exist"; else return null; string result = ""; if (args.op == "references") result = FindRefreneces(args.script, args.pos, args.context); else if (args.op.StartsWith("suggest_usings:")) result = FindUsings(args.script, args.op.Split(':').Last(), args.rich); else if (args.op == "resolve") result = Resolve(args.script, args.pos, args.rich); else if (args.op == "completion") result = GetCompletion(args.script, args.pos, args.doc); else if (args.op.StartsWith("tooltip:")) result = GetTooltip(args.script, args.pos, args.op.Split(':').Last(), args.short_hinted_tooltips == 1); else if (args.op.StartsWith("memberinfo")) result = GetMemberInfo(args.script, args.pos, args.collapseOverloads); else if (args.op.StartsWith("signaturehelp")) result = GetSignatureHelp(args.script, args.pos); else if (args.op == "project") result = GenerateProjectFor(args.script); else if (args.op == "codemap") result = CodeMap(args.script, args.rich, false); else if (args.op == "codemap_vscode") result = CodeMap(args.script, args.rich, vsCodeSerialization: true); else if (args.op == "format") { Output.WriteLine("FormatCode>"); int caretPos = args.pos; var formattedCode = FormatCode(args.script, ref caretPos); Output.WriteLine("<FormatCode"); result = $"{caretPos}\n{formattedCode}"; } if (string.IsNullOrEmpty(result)) return "<null>"; else return result; } catch (Exception e) { return "<error>" + e; } finally { Autocompleter.Language = "C#"; } } internal static string Resolve(string script, int offset, bool rich_serialization) { Output.WriteLine("Resolve"); DomRegion region = ResolveRaw(script, offset); fullyLoaded = true; if (rich_serialization) { return DomRegion.Serialize(region); } else { var result = new StringBuilder(); result.AppendLine("file:" + region.FileName); result.AppendLine("line:" + region.BeginLine); return result.ToString(); } } static string GetAssociatedCompletionContext(string directive) { return directive.FirstMatch(("//css_inc", ".cs"), ("//css_ac", "style"), ("//css_autoclass", "style"), ("//css_include", ".cs"), ("//css_ref", ".dll|.exe"), ("//css_reference", ".dll|.exe")); } internal static bool ParseAsCssDirective(string code, int offset, Action<string> onDirective, Action<string, string, string> onDirectiveArg, bool ignoreEmptyArgs = true) { string word = code.WordAt(offset, true); string line = code.LineAt(offset); if (word.StartsWith("//css_") || line.TrimStart().StartsWith("//css_")) { var directive = line.TrimStart().WordAt(2, true); string extensions = GetAssociatedCompletionContext(directive); var arg = word; if (arg.IsEmpty() && ignoreEmptyArgs) { onDirective(directive); } else if (word.StartsWith("//css_")) { onDirective(directive); } else { if (extensions == null) // directive that does not include file { onDirective(directive); } else { onDirectiveArg(directive, word, extensions); } } return true; } return false; } internal static string LookopDirectivePath(SourceInfo script, int offset, string directive, string word, string extensions = null) { extensions = extensions ?? GetAssociatedCompletionContext(directive); if (extensions != null && word.HasText()) // file of the //css_inc or //css_ref directive { bool ignoreCase = Utils.IsWinows; var probing_dirs = CSScriptHelper.GenerateProjectFor(script) .SearchDirs; var match = probing_dirs.Select(dir => { if (Directory.Exists(dir)) return Directory.GetFiles(dir, "*") .FirstOrDefault(file => { return Path.GetFileName(file).IsSameAs(word, ignoreCase) || (Path.GetFileNameWithoutExtension(file).IsSameAs(word, ignoreCase) && extensions.Contains(Path.GetExtension(file))); }); else return null; }) .FirstOrDefault(x => x != null); return match; } return null; } internal static string[] LookupDirectivePaths(SourceInfo script, int offset, string directive, string word, string extensions) { if (extensions != null) { return CSScriptHelper.GenerateProjectFor(script) .SearchDirs .Where(dir => Directory.Exists(dir)) .SelectMany(dir => extensions.Split('|').Select(x => new { ProbingDir = dir, FileExtension = x })) .SelectMany(x => Directory.GetFiles(x.ProbingDir, "*" + x.FileExtension)) .Where(x => x != script.File) .ToArray(); } return new string[0]; } internal static DomRegion ResolveRaw(string scriptFile, int offset) { var script = new SourceInfo(scriptFile); if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); DomRegion region = DomRegion.Empty; ParseAsCssDirective(script.Content, offset, directive => { region = CssSyntax.Resolve(directive); }, (directive, arg, extensions) => { if (LookopDirectivePath(script, offset, directive, arg) is string file) region = new DomRegion { BeginColumn = -1, BeginLine = -1, EndLine = -1, FileName = file, IsEmpty = false }; else region = CssSyntax.Resolve(directive); }); if (region.IsEmpty) { bool decorated = false; if (!script.RawFile.EndsWith(".g.cs")) decorated = CSScriptHelper.DecorateIfRequired(ref script.Content, ref offset); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); region = Autocompleter.ResolveSymbol(script.Content, offset, script.File, project.Refs, sources); if (decorated && region.FileName == script.File) CSScriptHelper.Undecorate(script.Content, ref region); } return region; } static void PKill(int pid, string childNameHint = null) { try { bool isLinux = Environment.OSVersion.Platform == PlatformID.Unix; bool isMac = Environment.OSVersion.Platform == PlatformID.MacOSX; if (!isLinux && !isMac && childNameHint != null) System.Diagnostics.Process.GetProcessById(pid)?.KillGroup(p => p.ProcessName.IsSameAs(childNameHint, true)); else System.Diagnostics.Process.GetProcessById(pid)?.Kill(); } catch { } } internal static string FindRefreneces(string scriptFile, int offset, string context) { Output.WriteLine("FindRefreneces"); var script = new SourceInfo(scriptFile); if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); bool decorated = false; if (!script.RawFile.EndsWith(".g.cs")) decorated = CSScriptHelper.DecorateIfRequired(ref script.Content, ref offset); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); var regions = new List<string>(); if (context == "all") // include definition and constructors { DomRegion[] refs = Autocompleter.GetSymbolSourceRefs(script.Content, offset, script.File, project.Refs, sources); foreach (DomRegion item in refs) { DomRegion region = item; if (decorated && item.FileName == script.File) { CSScriptHelper.Undecorate(script.Content, ref region); } regions.Add($"{item.FileName}({region.BeginLine},{item.BeginColumn}): ..."); } } regions.AddRange(Autocompleter.FindReferences(script.Content, offset, script.File, project.Refs, sources)); fullyLoaded = true; return regions.Distinct().JoinBy("\n"); } internal static string FindUsings(string scriptFile, string word, bool rich_serialization) { Output.WriteLine("FindUsings"); var script = new SourceInfo(scriptFile); if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)); var regions = Autocompleter.GetNamespacesFor(script.Content, word, project.Refs, sources); fullyLoaded = true; if (rich_serialization) return regions.Select(Intellisense.Common.TypeInfo.Serialize).JoinSerializedLines(); else return regions.Select(x => x.Namespace).JoinBy("\n"); } internal static string FormatCode(string script, ref int caret) { Output.WriteLine("FormatCode"); string code = File.ReadAllText(script); if (code.IsEmpty()) throw new Exception("The file containing code is empty"); bool escape_vs_template_var = code.Contains("$safeprojectname$"); if (escape_vs_template_var) code = code.Replace("$safeprojectname$", "_safeprojectname_"); string formattedCode = RoslynIntellisense.Formatter.FormatHybrid(code, "code.cs"); if (escape_vs_template_var) formattedCode = formattedCode.Replace("_safeprojectname_", "$safeprojectname$"); caret = SyntaxMapper.MapAbsPosition(code, caret, formattedCode); fullyLoaded = true; return formattedCode; } internal static string CodeMap(string script, bool nppSerialization, bool vsCodeSerialization) { csscript.Log("CodeMap"); bool vs_code = vsCodeSerialization; bool sublime = !vsCodeSerialization && !nppSerialization; string code = File.ReadAllText(script); if (code.IsEmpty()) throw new Exception("The file containing code is empty"); CodeMapItem[] members = CSScriptHelper.GetMapOf(code, nppSerialization).OrderBy(x => x.ParentDisplayName).ToArray(); fullyLoaded = true; if (nppSerialization) { return members.Select(CodeMapItem.Serialize).JoinSerializedLines(); } if (vs_code) { // https://github.com/oleg-shilo/codemap.vscode/wiki/Adding-custom-mappers // [indent]<name>|<line>|<icon> //see "static AutoCompiler.CodeMapItem[] GetMapOfCSharp(string code, bool decorated)" for possible MemberType var result = new StringBuilder(); var lines = members.Select(x => new { ParentType = (x.ParentDisplayName).Trim(), ParentTypeIcon = x.ParentDisplayType == "interface" ? "interface" : "class", Indent = " ", Name = x.DisplayName, Line = x.Line, Icon = (x.MemberType == "Enum" ? "class" : x.MemberType == "Method" ? "function" : x.MemberType == "Property" ? "property" : x.MemberType == "Field" ? "field" : "none") }); if (lines.Any()) { foreach (var group in lines.GroupBy(x => x.ParentType)) { bool first = true; foreach (var item in group) { var parentType = group.Key; if (first) { // do not pass any line number for class as it may be declared // at multiple locations (e.g. partial classes) first = false; result.AppendLine($"{parentType}||{item.ParentTypeIcon}"); } result.AppendLine($"{item.Indent}{item.Name}|{item.Line}|{item.Icon}"); } } } return result.ToString().Trim(); } if (sublime) { var result = new StringBuilder(); var lines = members.Select(x => { return new { Type = (x.ParentDisplayType + " " + x.ParentDisplayName).Trim(), Content = " " + x.DisplayName, Line = x.Line }; }); if (lines.Any()) { int maxLenghth = lines.Select(x => x.Type.Length).Max(); maxLenghth = Math.Max(maxLenghth, lines.Select(x => x.Content.Length).Max()); string prevType = null; foreach (var item in lines) { if (prevType != item.Type) { result.AppendLine(); result.AppendLine(item.Type); } prevType = item.Type; var suffix = new string(' ', maxLenghth - item.Content.Length); result.AppendLine($"{item.Content}{suffix} :{item.Line}"); } } return result.ToString().Trim(); } return null; } internal static string GetCompletion(string script, int caret, bool includDocumentation = false) { Output.WriteLine("GetCompletion"); var result = new StringBuilder(); foreach (ICompletionData item in GetCompletionRaw(script, caret, includDocumentation)) { string type = item.CompletionType.ToString().Replace("_event", "event").Replace("_namespace", "namespace"); string completion = item.CompletionText; string display = item.DisplayText; string documentation = item.Tag as string; if (item.CompletionType == CompletionType.method) { if (item.HasOverloads) { display += "(...)"; //completion += "("; } else { if (item.InvokeParameters.Count() == 0) { display += "()"; completion += "()"; } else { display += "(..)"; //completion += "("; } } } var extra = ""; if (includDocumentation && documentation.HasText()) { // VSCode is the one that accepts the documentation extra = $"|{documentation.EscapeLB()}"; completion = completion.EscapeLB(); } result.AppendLine($"{display}\t{type}|{completion}{extra}"); } fullyLoaded = true; //Console.WriteLine(">>>>>" + result.ToString().Trim()); return result.ToString().Trim(); } internal static IEnumerable<ICompletionData> GetCompletionRaw(string scriptFile, int caret, bool includDocumentation = false) { var script = new SourceInfo(scriptFile); if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); IEnumerable<ICompletionData> completions = null; bool wasHandled = ParseAsCssDirective(script.Content, caret, (directive) => { completions = CssCompletionData.AllDirectives; }, (directive, arg, extensions) => { if (directive.OneOf("//css_ac", "//css_autoclass")) { completions = new[]{ new CssCompletionData { CompletionText = "freestyle", DisplayText = "freestyle", Description = "Free style code without any entry point.", CompletionType = CompletionType.directive }}; } else completions = LookupDirectivePaths(script, caret, directive, arg, extensions) .Select(file => new CssCompletionData { CompletionText = Path.GetFileName(file), DisplayText = Path.GetFileName(file), Description = "File: " + file, CompletionType = CompletionType.file }); }, ignoreEmptyArgs: false); if (!wasHandled) { if (!script.RawFile.EndsWith(".g.cs")) CSScriptHelper.DecorateIfRequired(ref script.Content, ref caret); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); completions = Autocompleter.GetAutocompletionFor(script.Content, caret, project.Refs, sources, includDocumentation); var count = completions.Count(); } return completions; } static internal bool fullyLoaded = false; internal static string GetTooltip(string scriptFile, int caret, string hint, bool shortHintedTooltips) { // Simplified API for ST3 Output.WriteLine("GetTooltip"); //Console.WriteLine("hint: " + hint); string result = null; var script = new SourceInfo(scriptFile); if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); void loockupDirective(string directive) { var css_directive = CssCompletionData.AllDirectives .FirstOrDefault(x => x.DisplayText == directive); if (css_directive != null) { result = $"Directive: {css_directive.DisplayText}\n{css_directive.Description}"; result = result.NormalizeLineEnding().Replace("\r\n\r\n", "\r\n").TrimEnd(); } }; ParseAsCssDirective(script.Content, caret, loockupDirective, (directive, arg, extensions) => { if (LookopDirectivePath(script, caret, directive, arg) is string file) result = $"File: {file}"; else loockupDirective(directive); }); if (result.HasText()) { return result; } if (!script.RawFile.EndsWith(".g.cs")) CSScriptHelper.DecorateIfRequired(ref script.Content, ref caret); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); int methodStartPosTemp; var items = Autocompleter.GetMemberInfo(script.Content, caret, out methodStartPosTemp, project.Refs, sources, includeOverloads: hint.HasAny()); fullyLoaded = true; if (hint.HasAny()) { if (shortHintedTooltips) items = items.Select(x => x.Split('\n').FirstOrDefault()).ToArray(); int count = hint.Split(',').Count(); result = items.FirstOrDefault(x => { return SyntaxMapper.GetArgumentCount(x) == count; }) ?? items.FirstOrDefault(); bool hideOverloadsSummary = false; if (result != null && hideOverloadsSummary) { var lines = result.Split('\n').Select(x => x.TrimEnd('\r')).ToArray(); //(+ 1 overloads) if (lines[0].EndsWith(" overloads)")) { try { lines[0] = lines[0].Split(new[] { "(+" }, StringSplitOptions.None).First().Trim(); } catch { } } result = lines.JoinBy("\n"); } } else result = items.FirstOrDefault(); if (result.HasText()) result = result.NormalizeLineEnding().Replace("\r\n\r\n", "\r\n").TrimEnd(); return result; } static string ReadAllText(string file) { // Retrying for reading source file which may be locked by VSCode int attempts = 0; try { attempts++; return File.ReadAllText(file); } catch (Exception) { Thread.Sleep(200); if (attempts > 3) throw; } // The next line will never be called. // It's here just to satisfy the compiler. // Caching 'Exception e' may alter the trace stack so throwing directly from catch clause. throw new Exception($"Cannot read '{file}'"); } internal static string GetSignatureHelp(string scriptFile, int caret) { Output.WriteLine("GetSignatureHelp"); var script = new SourceInfo(scriptFile); string result = null; if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); if (!script.RawFile.EndsWith(".g.cs")) CSScriptHelper.DecorateIfRequired(ref script.Content, ref caret); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != project.Script) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); string bestMatchIndex; var items = Autocompleter.GetMethodSignatures(script.Content, caret, out bestMatchIndex, project.Refs, sources); result = $"{bestMatchIndex}\r\n" + items.Select(x => x.EscapeLB()) .JoinSerializedLines(); return result; } internal static string GetMemberInfo(string scriptFile, int caret, bool collapseOverloads) { // Complete API for N++ Output.WriteLine("GetMemberInfo"); //Console.WriteLine("hint: " + hint); var script = new SourceInfo(scriptFile); string result = null; if (script.Content.IsEmpty()) throw new Exception("The file containing code is empty"); void loockupDirective(string directive) { var css_directive = CssCompletionData.AllDirectives .FirstOrDefault(x => x.DisplayText == directive); if (css_directive != null) { result = $"Directive: {css_directive.DisplayText}\n{css_directive.Description}"; result = result.NormalizeLineEnding().Replace("\r\n\r\n", "\r\n").TrimEnd(); } }; ParseAsCssDirective(script.Content, caret, loockupDirective, (directive, arg, extensions) => { if (LookopDirectivePath(script, caret, directive, arg) is string file) result = $"File: {file}"; else loockupDirective(directive); }); if (result.HasText()) { return MemberInfoData.Serialize(new MemberInfoData { Info = result }); } if (!script.RawFile.EndsWith(".g.cs")) CSScriptHelper.DecorateIfRequired(ref script.Content, ref caret); Project project = CSScriptHelper.GenerateProjectFor(script); var sources = project.Files .Where(f => f != script.File) .Select(f => new Tuple<string, string>(File.ReadAllText(f), f)) .ToArray(); int methodStartPosTemp; var items = Autocompleter.GetMemberInfo(script.Content, caret, out methodStartPosTemp, project.Refs, sources, includeOverloads: !collapseOverloads); if (collapseOverloads) items = items.Take(1); result = items.Select(x => new MemberInfoData { Info = x, MemberStartPosition = methodStartPosTemp }) .Select(MemberInfoData.Serialize) .JoinSerializedLines(); return result; } static string GenerateProjectFor(string script) { //MessageBox.Show(typeof(Project).Assembly.Location, typeof(Project).Assembly.GetName().ToString()); var result = new StringBuilder(); Project project = CSScriptHelper.GenerateProjectFor(new SourceInfo(script)); foreach (string file in project.Files) result.AppendLine($"file:{file}"); foreach (string file in project.Refs) result.AppendLine($"ref:{file}"); return result.ToString().Trim(); } public static string testAutoClassCode = @"//css_ac using System; using System.Diagnostics; void main(string[] args) { Console.WriteLine(""Hello World!""); }"; public static string testFreestyleCode = @"//css_ac freestyle using System; using System.Diagnostics; Console.WriteLine(""Hello World!""); "; public static string testCode = @"using System; using System.Windows.Forms; class Script { [STAThread] static public void Main(string[] args) { MessageBox.Show(""Just a test!""); for (int i = 0; i<args.Length; i++) { var t = args[0].Length.ToString().GetHashCode(); Console.WriteLine(args[i]); } } }"; public static string testCode7b = preloadCode; public const string preloadCode = @" using System; using System.Linq; using System.Collections.Generic; using System.Windows.Forms; using static dbg; // to use 'print' instead of 'dbg.print' class Script { static public void Main(string[] args) { (string message, int version) setup_say_hello() { return (""Hello from C#"", 7); } var info = setup_say_hello(); print(info.message, info.version); print(Environment.GetEnvironmentVariables() .Cast<object>() .Take(5)); Console.WriteLine(777); Form form = new // Forms f = new Form(); // f.DialogResult = // System.IO.StreamReader file = } }"; public static string testCode7 = @"using System; using System.Windows.Forms; class Script { [STAThread] static public void Main(string[] args) { MessageBox.Show(""Just a test!""); for (int i = 0; i<args.Length; i++) { var t = args[0].Length.ToString().GetHashCode(); Console.WriteLine(args[i]); void test() { Console.WriteLine(""Local function - C#7""); } tes // var tup = (1,2); } } }"; public static string testCodeClass = @" using System; class Script { public Script() { } public Script(string context) { } public Script(int context) { } static Script() { } static public void Main() { var script = new Script(); } }"; } }
// 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.Threading; using System.Threading.Tasks; namespace System.IO.Tests { public class UmsTests { internal static void UmsInvariants(UnmanagedMemoryStream stream) { Assert.False(stream.CanTimeout); } internal static void ReadUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.True(stream.CanRead); Assert.False(stream.CanWrite); Assert.True(stream.CanSeek); Assert.Throws<NotSupportedException>(() => stream.SetLength(1000)); } internal static void WriteUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.False(stream.CanRead); Assert.True(stream.CanWrite); Assert.True(stream.CanSeek); } internal static void ReadWriteUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.True(stream.CanRead); Assert.True(stream.CanWrite); Assert.True(stream.CanSeek); } [Fact] public static void PositionTests() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = -1; }); // "Non-negative number required." Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = unchecked(Int64.MaxValue + 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = Int32.MinValue; }); stream.Position = stream.Length; Assert.Equal(stream.Position, stream.Length); stream.Position = stream.Capacity; Assert.Equal(stream.Position, stream.Capacity); int mid = (int)stream.Length / 2; stream.Position = mid; Assert.Equal(stream.Position, mid); } } [Fact] public static void LengthTests() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<IOException>(() => stream.SetLength(1001)); Assert.Throws<ArgumentOutOfRangeException>(() => stream.SetLength(SByte.MinValue)); const long expectedLength = 500; stream.Position = 501; stream.SetLength(expectedLength); Assert.Equal(expectedLength, stream.Length); Assert.Equal(expectedLength, stream.Position); } } [Fact] public static void SeekTests() { const int length = 1000; using (var manager = new UmsManager(FileAccess.ReadWrite, length)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<IOException>(() => stream.Seek(unchecked(Int32.MaxValue + 1), SeekOrigin.Begin)); Assert.Throws<IOException>(() => stream.Seek(Int64.MinValue, SeekOrigin.End)); Assert.Throws<ArgumentException>(() => stream.Seek(0, (SeekOrigin)7)); // Invalid seek origin stream.Seek(10, SeekOrigin.Begin); Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin)); // An attempt was made to move the position before the beginning of the stream Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-(stream.Position + 1), SeekOrigin.Current)); // An attempt was made to move the position before the beginning of the stream Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-(stream.Length + 1), SeekOrigin.End)); // "An attempt was made to move the position before the beginning of the stream." Assert.Equal(10, stream.Position); // Seek from SeekOrigin.Begin stream.Seek(0, SeekOrigin.Begin); for (int position = 0; position < stream.Length; position++) { stream.Seek(position, SeekOrigin.Begin); Assert.Equal(position, stream.Position); } for (int position = (int)stream.Length; position >= 0; position--) { stream.Seek(position, SeekOrigin.Begin); Assert.Equal(position, stream.Position); } stream.Seek(0, SeekOrigin.Begin); // Seek from SeekOrigin.End for (int position = 0; position < stream.Length; position++) { stream.Seek(-position, SeekOrigin.End); Assert.Equal(length - position, stream.Position); } for (int position = (int)stream.Length; position >= 0; position--) { stream.Seek(-position, SeekOrigin.End); Assert.Equal(length - position, stream.Position); } // Seek from SeekOrigin.Current stream.Seek(0, SeekOrigin.Begin); for (int position = 0; position < stream.Length; position++) { stream.Seek(1, SeekOrigin.Current); Assert.Equal(position + 1, stream.Position); } for (int position = (int)stream.Length; position > 0; position--) { stream.Seek(-1, SeekOrigin.Current); Assert.Equal(position - 1, stream.Position); } } } [Fact] public static void CannotUseStreamAfterDispose() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); stream.Dispose(); Assert.False(stream.CanRead); Assert.False(stream.CanWrite); Assert.False(stream.CanSeek); Assert.Throws<ObjectDisposedException>(() => { long x = stream.Capacity; }); Assert.Throws<ObjectDisposedException>(() => { long y = stream.Length; }); Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(2); }); Assert.Throws<ObjectDisposedException>(() => { long z = stream.Position; }); Assert.Throws<ObjectDisposedException>(() => { stream.Position = 2; }); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin)); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Current)); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.End)); Assert.Throws<ObjectDisposedException>(() => stream.Flush()); Assert.Throws<ObjectDisposedException>(() => stream.FlushAsync(CancellationToken.None).GetAwaiter().GetResult()); byte[] buffer = ArrayHelpers.CreateByteArray(10); Assert.Throws<ObjectDisposedException>(() => stream.Read(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => stream.ReadAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult()); Assert.Throws<ObjectDisposedException>(() => stream.ReadByte()); Assert.Throws<ObjectDisposedException>(() => stream.WriteByte(0)); Assert.Throws<ObjectDisposedException>(() => stream.Write(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => stream.WriteAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult()); } } [Fact] public static void CopyToTest() { byte[] testData = ArrayHelpers.CreateByteArray(8192); using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Position = 0; ums.CopyTo(destination); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; ums.CopyTo(destination, 1); Assert.Equal(testData, destination.ToArray()); } // copy to disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Dispose(); Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination)); } // copy from disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); ums.Dispose(); MemoryStream destination = new MemoryStream(); Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination)); } // copying to non-writeable stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination)); } // copying from non-readable stream should throw using (var manager = new UmsManager(FileAccess.Write, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.WriteUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination)); } } [Fact] public static async Task CopyToAsyncTest() { byte[] testData = ArrayHelpers.CreateByteArray(8192); using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Position = 0; await ums.CopyToAsync(destination); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; await ums.CopyToAsync(destination, 2); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; await ums.CopyToAsync(destination, 0x1000, new CancellationTokenSource().Token); Assert.Equal(testData, destination.ToArray()); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ums.CopyToAsync(destination, 0x1000, new CancellationToken(true))); } // copy to disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination)); } // copy from disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); ums.Dispose(); MemoryStream destination = new MemoryStream(); await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination)); } // cpoying to non-writeable stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination)); } // copying from non-readable stream should throw using (var manager = new UmsManager(FileAccess.Write, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.WriteUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Http.Headers { // The purpose of this type is to extract the handling of general headers in one place rather than duplicating // functionality in both HttpRequestHeaders and HttpResponseHeaders. internal sealed class HttpGeneralHeaders { private HttpHeaderValueCollection<string> _connection; private HttpHeaderValueCollection<string> _trailer; private HttpHeaderValueCollection<TransferCodingHeaderValue> _transferEncoding; private HttpHeaderValueCollection<ProductHeaderValue> _upgrade; private HttpHeaderValueCollection<ViaHeaderValue> _via; private HttpHeaderValueCollection<WarningHeaderValue> _warning; private HttpHeaderValueCollection<NameValueHeaderValue> _pragma; private HttpHeaders _parent; private bool _transferEncodingChunkedSet; private bool _connectionCloseSet; public CacheControlHeaderValue CacheControl { get { return (CacheControlHeaderValue)_parent.GetParsedValues(HttpKnownHeaderNames.CacheControl); } set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.CacheControl, value); } } public HttpHeaderValueCollection<string> Connection { get { return ConnectionCore; } } public bool? ConnectionClose { get { // Separated out into a static to enable access to TransferEncodingChunked // without the caller needing to force the creation of HttpGeneralHeaders // if it wasn't created for other reasons. return GetConnectionClose(_parent, this); } set { if (value == true) { _connectionCloseSet = true; ConnectionCore.SetSpecialValue(); } else { _connectionCloseSet = value != null; ConnectionCore.RemoveSpecialValue(); } } } internal static bool? GetConnectionClose(HttpHeaders parent, HttpGeneralHeaders headers) { // If we've already initialized the connection header value collection // and it contains the special value, or if we haven't and the headers contain // the parsed special value, return true. We don't just access ConnectionCore, // as doing so will unnecessarily initialize the collection even if it's not needed. if (headers?._connection != null) { if (headers._connection.IsSpecialValueSet) { return true; } } else if (parent.ContainsParsedValue(HttpKnownHeaderNames.Connection, HeaderUtilities.ConnectionClose)) { return true; } if (headers != null && headers._connectionCloseSet) { return false; } return null; } public DateTimeOffset? Date { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.Date, _parent); } set { _parent.SetOrRemoveParsedValue(HttpKnownHeaderNames.Date, value); } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { if (_pragma == null) { _pragma = new HttpHeaderValueCollection<NameValueHeaderValue>(HttpKnownHeaderNames.Pragma, _parent); } return _pragma; } } public HttpHeaderValueCollection<string> Trailer { get { if (_trailer == null) { _trailer = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Trailer, _parent, HeaderUtilities.TokenValidator); } return _trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return TransferEncodingCore; } } internal static bool? GetTransferEncodingChunked(HttpHeaders parent, HttpGeneralHeaders headers) { // If we've already initialized the transfer encoding header value collection // and it contains the special value, or if we haven't and the headers contain // the parsed special value, return true. We don't just access TransferEncodingCore, // as doing so will unnecessarily initialize the collection even if it's not needed. if (headers?._transferEncoding != null) { if (headers._transferEncoding.IsSpecialValueSet) { return true; } } else if (parent.ContainsParsedValue(HttpKnownHeaderNames.TransferEncoding, HeaderUtilities.TransferEncodingChunked)) { return true; } if (headers != null && headers._transferEncodingChunkedSet) { return false; } return null; } public bool? TransferEncodingChunked { get { // Separated out into a static to enable access to TransferEncodingChunked // without the caller needing to force the creation of HttpGeneralHeaders // if it wasn't created for other reasons. return GetTransferEncodingChunked(_parent, this); } set { if (value == true) { _transferEncodingChunkedSet = true; TransferEncodingCore.SetSpecialValue(); } else { _transferEncodingChunkedSet = value != null; TransferEncodingCore.RemoveSpecialValue(); } } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { if (_upgrade == null) { _upgrade = new HttpHeaderValueCollection<ProductHeaderValue>(HttpKnownHeaderNames.Upgrade, _parent); } return _upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { if (_via == null) { _via = new HttpHeaderValueCollection<ViaHeaderValue>(HttpKnownHeaderNames.Via, _parent); } return _via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { if (_warning == null) { _warning = new HttpHeaderValueCollection<WarningHeaderValue>(HttpKnownHeaderNames.Warning, _parent); } return _warning; } } private HttpHeaderValueCollection<string> ConnectionCore { get { if (_connection == null) { _connection = new HttpHeaderValueCollection<string>(HttpKnownHeaderNames.Connection, _parent, HeaderUtilities.ConnectionClose, HeaderUtilities.TokenValidator); } return _connection; } } private HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncodingCore { get { if (_transferEncoding == null) { _transferEncoding = new HttpHeaderValueCollection<TransferCodingHeaderValue>( HttpKnownHeaderNames.TransferEncoding, _parent, HeaderUtilities.TransferEncodingChunked); } return _transferEncoding; } } internal HttpGeneralHeaders(HttpHeaders parent) { Debug.Assert(parent != null); _parent = parent; } internal static void AddParsers(Dictionary<string, HttpHeaderParser> parserStore) { Debug.Assert(parserStore != null); parserStore.Add(HttpKnownHeaderNames.CacheControl, CacheControlHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.Connection, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.Date, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.Pragma, GenericHeaderParser.MultipleValueNameValueParser); parserStore.Add(HttpKnownHeaderNames.Trailer, GenericHeaderParser.TokenListParser); parserStore.Add(HttpKnownHeaderNames.TransferEncoding, TransferCodingHeaderParser.MultipleValueParser); parserStore.Add(HttpKnownHeaderNames.Upgrade, GenericHeaderParser.MultipleValueProductParser); parserStore.Add(HttpKnownHeaderNames.Via, GenericHeaderParser.MultipleValueViaParser); parserStore.Add(HttpKnownHeaderNames.Warning, GenericHeaderParser.MultipleValueWarningParser); } internal static void AddKnownHeaders(HashSet<string> headerSet) { Debug.Assert(headerSet != null); headerSet.Add(HttpKnownHeaderNames.CacheControl); headerSet.Add(HttpKnownHeaderNames.Connection); headerSet.Add(HttpKnownHeaderNames.Date); headerSet.Add(HttpKnownHeaderNames.Pragma); headerSet.Add(HttpKnownHeaderNames.Trailer); headerSet.Add(HttpKnownHeaderNames.TransferEncoding); headerSet.Add(HttpKnownHeaderNames.Upgrade); headerSet.Add(HttpKnownHeaderNames.Via); headerSet.Add(HttpKnownHeaderNames.Warning); } internal void AddSpecialsFrom(HttpGeneralHeaders sourceHeaders) { // Copy special values, but do not overwrite bool? chunked = TransferEncodingChunked; if (!chunked.HasValue) { TransferEncodingChunked = sourceHeaders.TransferEncodingChunked; } bool? close = ConnectionClose; if (!close.HasValue) { ConnectionClose = sourceHeaders.ConnectionClose; } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Diagnostics; using System.Diagnostics.Tracing; using System.Threading; using System.Threading.Tasks; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access the generic TaskAwaiter<> as TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> [StackTraceHidden] private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default); Debug.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsCompletedSuccessfully) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> [StackTraceHidden] private static void ThrowForNonSuccess(Task task) { Debug.Assert(task.IsCompleted, "Task must have been completed by now."); Debug.Assert(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: var oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Debug.Fail("Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Debug.Fail("Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Debug.Fail("There should be exceptions if we're Faulted."); throw task.Exception; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException(nameof(continuation)); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="stateMachineBox">The box to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { Debug.Assert(stateMachineBox != null); // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); } else { task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); } } /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Debug.Assert(task != null, "Need a task to wait on"); Debug.Assert(continuation != null, "Need a continuation to invoke when the wait completes"); if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } var log = TplEventSource.Log; if (log.IsEnabled()) { // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; // If this task's continuation is another task, get it. var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); log.TaskWaitBegin( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id, TplEventSource.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0)); } // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, (innerContinuation,innerTask) => { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(innerTask); } TplEventSource innerEtwLog = TplEventSource.Log; // ETW event for Task Wait End. Guid prevActivityId = new Guid(); bool bEtwLogEnabled = innerEtwLog.IsEnabled(); if (bEtwLogEnabled) { var currentTaskAtEnd = Task.InternalCurrent; innerEtwLog.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), innerTask.Id); // Ensure the continuation runs under the activity ID of the task that completed for the // case the antecedent is a promise (in the other cases this is already the case). if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(innerTask.Id), out prevActivityId); } // Invoke the original continuation provided to OnCompleted. innerContinuation(); if (bEtwLogEnabled) { innerEtwLog.TaskWaitContinuationComplete(innerTask.Id); if (innerEtwLog.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(prevActivityId); } }, task); } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct TaskAwaiter<TResult> : ICriticalNotifyCompletion, ITaskAwaiter { // WARNING: Unsafe.As is used to access TaskAwaiter<> as the non-generic TaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// TaskAwaiter or a TaskAwaiter`1. It must not be implemented by any other /// awaiters. /// </summary> internal interface ITaskAwaiter { } /// <summary> /// Marker interface used to know whether a particular awaiter is either a /// CTA.ConfiguredTaskAwaiter or a CTA`1.ConfiguredTaskAwaiter. It must not /// be implemented by any other awaiters. /// </summary> internal interface IConfiguredTaskAwaiter { } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access the generic ConfiguredTaskAwaiter as this. // Its layout must remain the same. /// <summary>The task being awaited.</summary> internal readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> internal readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, IConfiguredTaskAwaiter { // WARNING: Unsafe.As is used to access this as the non-generic ConfiguredTaskAwaiter. // Its layout must remain the same. /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Debug.Assert(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System; #if !ES_BUILD_AGAINST_DOTNET_V35 using Contract = System.Diagnostics.Contracts.Contract; #else using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract; #endif #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor; #endif #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace) #endif #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { // New in CLR4.0 internal enum ControllerCommand { // Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256 // The first 256 negative numbers are reserved for the framework. Update = 0, // Not used by EventPrividerBase. SendManifest = -1, Enable = -2, Disable = -3, }; /// <summary> /// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a /// controller callback) /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] internal partial class EventProvider : IDisposable { // This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what // subclasses of EventProvider use when creating efficient (but unsafe) version of // EventWrite. We do make it a nested type because we really don't expect anyone to use // it except subclasses (and then only rarely). public struct EventData { internal unsafe ulong Ptr; internal uint Size; internal uint Reserved; } /// <summary> /// A struct characterizing ETW sessions (identified by the etwSessionId) as /// activity-tracing-aware or legacy. A session that's activity-tracing-aware /// has specified one non-zero bit in the reserved range 44-47 in the /// 'allKeywords' value it passed in for a specific EventProvider. /// </summary> public struct SessionInfo { internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords internal int etwSessionId; // the machine-wide ETW session ID internal SessionInfo(int sessionIdBit_, int etwSessionId_) { sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; } } private static bool m_setInformationMissing; [SecurityCritical] UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function private long m_regHandle; // Trace Registration Handle private byte m_level; // Tracing Level private long m_anyKeywordMask; // Trace Enable Flags private long m_allKeywordMask; // Match all keyword #if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>) #endif private bool m_enabled; // Enabled flag from Trace callback private Guid m_providerId; // Control Guid internal bool m_disposed; // when true provider has unregistered [ThreadStatic] private static WriteEventErrorCode s_returnCode; // The last return code private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 64; private const int s_etwAPIMaxRefObjCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { //check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2, NullInput = 3, TooManyArgs = 4, Other = 5, }; // Because callbacks happen on registration, and we need the callbacks for those setup // we can't call Register in the constructor. // // Note that EventProvider should ONLY be used by EventSource. In particular because // it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise // you may get native callbacks during shutdown when we have destroyed the delegate. // EventSource has special logic to do this, no one else should be calling EventProvider. internal EventProvider() { } /// <summary> /// This method registers the controlGuid of this class with ETW. We need to be running on /// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some /// reason the ETW Register call failed a NotSupported exception will be thrown. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" /> // <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" /> // <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal unsafe void Register(Guid providerGuid) { m_providerId = providerGuid; uint status; m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack); status = EventRegister(ref m_providerId, m_etwCallback); if (status != 0) { throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status))); } } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1"> // <ReferencesCritical Name="Method: Deregister():Void" Ring="1" /> // </SecurityKernel> [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing arguement is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been allready disposed // if (m_disposed) return; // Disable the provider. m_enabled = false; // Do most of the work under a lock to avoid shutdown race. lock (EventListener.EventListenersLock) { // Double check if (m_disposed) return; Deregister(); m_disposed = true; } } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" /> // </SecurityKernel> // TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (m_regHandle != 0) { EventUnregister(); m_regHandle = 0; } } [System.Security.SecurityCritical] unsafe void EtwEnableCallBack( ref System.Guid sourceId, int controlCode, byte setLevel, long anyKeyword, long allKeyword, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, void* callbackContext ) { // This is an optional callback API. We will therefore ignore any failures that happen as a // result of turning on this provider as to not crash the app. // EventSource has code to validate whether initialization it expected to occur actually occurred try { ControllerCommand command = ControllerCommand.Update; IDictionary<string, string> args = null; bool skipFinalOnControllerCommand = false; if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER) { m_enabled = true; m_level = setLevel; m_anyKeywordMask = anyKeyword; m_allKeywordMask = allKeyword; // ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove // references to EnumerateTraceGuidsEx. This symbol is actually not used because // today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not. // However we put it in the #if so that we don't lose the fact that this feature // switch is at least partially independent of FEATURE_ACTIVITYSAMPLING #if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions(); foreach (var session in sessionsChanged) { int sessionChanged = session.Item1.sessionIdBit; int etwSessionId = session.Item1.etwSessionId; bool bEnabling = session.Item2; skipFinalOnControllerCommand = true; args = null; // reinitialize args for every session... // if we get more than one session changed we have no way // of knowing which one "filterData" belongs to if (sessionsChanged.Count > 1) filterData = null; // read filter data only when a session is being *added* byte[] data; int keyIndex; if (bEnabling && GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex)) { args = new Dictionary<string, string>(4); while (keyIndex < data.Length) { int keyEnd = FindNull(data, keyIndex); int valueIdx = keyEnd + 1; int valueEnd = FindNull(data, valueIdx); if (valueEnd < data.Length) { string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex); string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx); args[key] = value; } keyIndex = valueEnd + 1; } } // execute OnControllerCommand once for every session that has changed. OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId); } #endif } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER) { m_enabled = false; m_level = 0; m_anyKeywordMask = 0; m_allKeywordMask = 0; #if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING m_liveSessions = null; #endif } else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE) { command = ControllerCommand.SendManifest; } else return; // per spec you ignore commands you don't recognize. if (!skipFinalOnControllerCommand) OnControllerCommand(command, args, 0, 0); } catch (Exception) { // We want to ignore any failures that happen as a result of turning on this provider as to // not crash the app. } } // New in CLR4.0 protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { } protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } } protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } } protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } } static private int FindNull(byte[] buffer, int idx) { while (idx < buffer.Length && buffer[idx] != 0) idx++; return idx; } #if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING /// <summary> /// Determines the ETW sessions that have been added and/or removed to the set of /// sessions interested in the current provider. It does so by (1) enumerating over all /// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2) /// comparing the current list with a list it cached on the previous invocation. /// /// The return value is a list of tuples, where the SessionInfo specifies the /// ETW session that was added or remove, and the bool specifies whether the /// session was added or whether it was removed from the set. /// </summary> [System.Security.SecuritySafeCritical] private List<Tuple<SessionInfo, bool>> GetSessions() { List<SessionInfo> liveSessionList = null; GetSessionInfo((Action<int, long>) ((etwSessionId, matchAllKeywords) => GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList))); List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>(); // first look for sessions that have gone away (or have changed) // (present in the m_liveSessions but not in the new liveSessionList) if (m_liveSessions != null) { foreach (SessionInfo s in m_liveSessions) { int idx; if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 || (liveSessionList[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, false)); } } // next look for sessions that were created since the last callback (or have changed) // (present in the new liveSessionList but not in m_liveSessions) if (liveSessionList != null) { foreach (SessionInfo s in liveSessionList) { int idx; if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 || (m_liveSessions[idx].sessionIdBit != s.sessionIdBit)) changedSessionList.Add(Tuple.Create(s, true)); } } m_liveSessions = liveSessionList; return changedSessionList; } /// <summary> /// This method is the callback used by GetSessions() when it calls into GetSessionInfo(). /// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that /// GetSessionInfo() passes in. /// </summary> private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords, ref List<SessionInfo> sessionList) { uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords)); // an ETW controller that specifies more than the mandated bit for our EventSource // will be ignored... if (bitcount(sessionIdBitMask) > 1) return; if (sessionList == null) sessionList = new List<SessionInfo>(8); if (bitcount(sessionIdBitMask) == 1) { // activity-tracing-aware etw session sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask) + 1, etwSessionId)); } else { // legacy etw session sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All) + 1, etwSessionId)); } } /// <summary> /// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid' /// for the current process ID, calling 'action' for each session, and passing it the /// ETW session and the 'AllKeywords' the session enabled for the current provider. /// </summary> [System.Security.SecurityCritical] private unsafe void GetSessionInfo(Action<int, long> action) { // We wish the EventSource package to be legal for Windows Store applications. // Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here // and use the information in the registry instead. This means that ETW controllers // that do not publish their intent to the registry (basically all controllers EXCEPT // TraceEventSesion) will not work properly // However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus // does not have this issue. #if ES_SESSION_INFO int buffSize = 256; // An initial guess that probably works most of the time. byte* buffer; for (; ; ) { var space = stackalloc byte[buffSize]; buffer = space; var hr = 0; fixed (Guid* provider = &m_providerId) { hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo, provider, sizeof(Guid), buffer, buffSize, ref buffSize); } if (hr == 0) break; if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */) return; } var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer; var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1]; int processId = unchecked((int)Win32Native.GetCurrentProcessId()); // iterate over the instances of the EventProvider in all processes for (int i = 0; i < providerInfos->InstanceCount; i++) { if (providerInstance->Pid == processId) { var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1]; // iterate over the list of active ETW sessions "listening" to the current provider for (int j = 0; j < providerInstance->EnableCount; j++) action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword); } if (providerInstance->NextOffset == 0) break; Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize); var structBase = (byte*)providerInstance; providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset]; } #else #if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds... // Determine our session from what is in the registry. string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"Software" + @"\Wow6432Node" + regKey; else regKey = @"Software" + regKey; var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey); if (key != null) { foreach (string valueName in key.GetValueNames()) { if (valueName.StartsWith("ControllerData_Session_")) { string strId = valueName.Substring(23); // strip of the ControllerData_Session_ int etwSessionId; if (int.TryParse(strId, out etwSessionId)) { // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); var data = key.GetValue(valueName) as byte[]; if (data != null) { var dataAsString = System.Text.Encoding.UTF8.GetString(data); int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword"); if (0 <= keywordIdx) { int startIdx = keywordIdx + 18; int endIdx = dataAsString.IndexOf('\0', startIdx); string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx); int keywordBit; if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit)) action(etwSessionId, 1L << keywordBit); } } } } } } #endif #endif } /// <summary> /// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId' /// or -1 if the value is not present. /// </summary> private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId) { if (sessions == null) return -1; // for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile // on coreclr as well for (int i = 0; i < sessions.Count; ++i) if (sessions[i].etwSessionId == etwSessionId) return i; return -1; } #endif /// <summary> /// Gets any data to be passed from the controller to the provider. It starts with what is passed /// into the callback, but unfortunately this data is only present for when the provider is active /// at the time the controller issues the command. To allow for providers to activate after the /// controller issued a command, we also check the registry and use that to get the data. The function /// returns an array of bytes representing the data, the index into that byte array where the data /// starts, and the command being issued associated with that data. /// </summary> [System.Security.SecurityCritical] private unsafe bool GetDataFromController(int etwSessionId, UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData, out ControllerCommand command, out byte[] data, out int dataStart) { data = null; dataStart = 0; if (filterData == null) { #if (!ES_BUILD_PCL && !PROJECTN && !FEATURE_PAL) string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}"; if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8) regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey; else regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey; string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture); // we need to assert this permission for partial trust scenarios (new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert(); data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[]; if (data != null) { // We only used the persisted data from the registry for updates. command = ControllerCommand.Update; return true; } #endif } else { if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024) { data = new byte[filterData->Size]; Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length); } command = (ControllerCommand)filterData->Type; return true; } command = ControllerCommand.Update; return false; } /// <summary> /// IsEnabled, method used to test if provider is enabled /// </summary> public bool IsEnabled() { return m_enabled; } /// <summary> /// IsEnabled, method used to test if event is enabled /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (!m_enabled) { return false; } // This also covers the case of Level == 0. if ((level <= m_level) || (m_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & m_anyKeywordMask) != 0) && ((keywords & m_allKeywordMask) == m_allKeywordMask))) { return true; } } return false; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public static WriteEventErrorCode GetLastWriteEventError() { return s_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA: s_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY: s_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" /> // <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" /> // <UsesUnsafeCode Name="Local longptr of type: Int64*" /> // <UsesUnsafeCode Name="Local uintptr of type: UInt32*" /> // <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" /> // <UsesUnsafeCode Name="Local charptr of type: Char*" /> // <UsesUnsafeCode Name="Local byteptr of type: Byte*" /> // <UsesUnsafeCode Name="Local shortptr of type: Int16*" /> // <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" /> // <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" /> // <UsesUnsafeCode Name="Local floatptr of type: Single*" /> // <UsesUnsafeCode Name="Local doubleptr of type: Double*" /> // <UsesUnsafeCode Name="Local boolptr of type: Boolean*" /> // <UsesUnsafeCode Name="Local guidptr of type: Guid*" /> // <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" /> // <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" /> // <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" /> // <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" /> // </SecurityKernel> [System.Security.SecurityCritical] private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry) dataBuffer - storage buffer for storing user data, needed because cant get the address of the object (updated to point to the next empty entry) Return Value: null if the object is a basic type other than string or byte[]. String otherwise --*/ { Again: dataDescriptor->Reserved = 0; string sRet = data as string; byte[] blobRet = null; if (sRet != null) { dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } else if ((blobRet = data as byte[]) != null) { // first store array length *(int*)dataBuffer = blobRet.Length; dataDescriptor->Ptr = (ulong)dataBuffer; dataDescriptor->Size = 4; totalEventSize += dataDescriptor->Size; // then the array parameters dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; dataDescriptor->Size = (uint)blobRet.Length; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->Ptr = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptr = (int*)dataBuffer; *intptr = (int)data; dataDescriptor->Ptr = (ulong)intptr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->Ptr = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->Ptr = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->Ptr = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->Ptr = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->Ptr = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->Ptr = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->Ptr = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->Ptr = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->Ptr = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->Ptr = (ulong)doubleptr; } else if (data is bool) { // WIN32 Bool is 4 bytes dataDescriptor->Size = 4; int* intptr = (int*)dataBuffer; if (((bool)data)) { *intptr = 1; } else { *intptr = 0; } dataDescriptor->Ptr = (ulong)intptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->Ptr = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->Ptr = (ulong)decimalptr; } else if (data is DateTime) { const long UTCMinTicks = 504911232000000000; long dateTimeTicks = 0; // We cannot translate dates sooner than 1/1/1601 in UTC. // To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks if (((DateTime)data).Ticks > UTCMinTicks) dateTimeTicks = ((DateTime)data).ToFileTimeUtc(); dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = dateTimeTicks; dataDescriptor->Ptr = (ulong)longptr; } else { if (data is System.Enum) { Type underlyingType = Enum.GetUnderlyingType(data.GetType()); if (underlyingType == typeof(int)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt32(null); #else data = (int)data; #endif goto Again; } else if (underlyingType == typeof(long)) { #if !ES_BUILD_PCL data = ((IConvertible)data).ToInt64(null); #else data = (long)data; #endif goto Again; } } // To our eyes, everything else is a just a string if (data == null) sRet = ""; else sRet = data.ToString(); dataDescriptor->Size = ((uint)sRet.Length + 1) * 2; } totalEventSize += dataDescriptor->Size; // advance buffers dataDescriptor++; dataBuffer += s_basicTypeAllocationBufferSize; return (object)sRet ?? (object)blobRet; } /// <summary> /// WriteEvent, method to write a parameters with event schema properties /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID GUID to log /// </param> /// <param name="childActivityID"> /// childActivityID is marked as 'related' to the current activity ID. /// </param> /// <param name="eventPayload"> /// Payload for the ETW event. /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local pdata of type: Char*" /> // <UsesUnsafeCode Name="Local userData of type: EventData*" /> // <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" /> // <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" /> // <UsesUnsafeCode Name="Local v0 of type: Char*" /> // <UsesUnsafeCode Name="Local v1 of type: Char*" /> // <UsesUnsafeCode Name="Local v2 of type: Char*" /> // <UsesUnsafeCode Name="Local v3 of type: Char*" /> // <UsesUnsafeCode Name="Local v4 of type: Char*" /> // <UsesUnsafeCode Name="Local v5 of type: Char*" /> // <UsesUnsafeCode Name="Local v6 of type: Char*" /> // <UsesUnsafeCode Name="Local v7 of type: Char*" /> // <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload) { int status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { int argCount = 0; unsafe { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } uint totalEventSize = 0; int index; int refObjIndex = 0; List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount); List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount); EventData* userData = stackalloc EventData[2 * argCount]; EventData* userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObject method. // bool hasNonStringRefArgs = false; for (index = 0; index < eventPayload.Length; index++) { if (eventPayload[index] != null) { object supportedRefObj; supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize); if (supportedRefObj != null) { // EncodeObject advanced userDataPtr to the next empty slot int idx = (int)(userDataPtr - userData - 1); if (!(supportedRefObj is string)) { if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments) { s_returnCode = WriteEventErrorCode.TooManyArgs; return false; } hasNonStringRefArgs = true; } dataRefObj.Add(supportedRefObj); refObjPosition.Add(idx); refObjIndex++; } } else { s_returnCode = WriteEventErrorCode.NullInput; return false; } } // update argCount based on actual number of arguments written to 'userData' argCount = (int)(userDataPtr - userData); if (totalEventSize > s_traceEventMaximumSize) { s_returnCode = WriteEventErrorCode.EventTooBig; return false; } // the optimized path (using "fixed" instead of allocating pinned GCHandles if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount)) { // Fast path: at most 8 string arguments // ensure we have at least s_etwAPIMaxStringCount in dataString, so that // the "fixed" statement below works while (refObjIndex < s_etwAPIMaxRefObjCount) { dataRefObj.Add(null); ++refObjIndex; } // // now fix any string arguments and set the pointer on the data descriptor // fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3], v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7]) { userDataPtr = (EventData*)userData; if (dataRefObj[0] != null) { userDataPtr[refObjPosition[0]].Ptr = (ulong)v0; } if (dataRefObj[1] != null) { userDataPtr[refObjPosition[1]].Ptr = (ulong)v1; } if (dataRefObj[2] != null) { userDataPtr[refObjPosition[2]].Ptr = (ulong)v2; } if (dataRefObj[3] != null) { userDataPtr[refObjPosition[3]].Ptr = (ulong)v3; } if (dataRefObj[4] != null) { userDataPtr[refObjPosition[4]].Ptr = (ulong)v4; } if (dataRefObj[5] != null) { userDataPtr[refObjPosition[5]].Ptr = (ulong)v5; } if (dataRefObj[6] != null) { userDataPtr[refObjPosition[6]].Ptr = (ulong)v6; } if (dataRefObj[7] != null) { userDataPtr[refObjPosition[7]].Ptr = (ulong)v7; } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); } } else { // Slow path: use pinned handles userDataPtr = (EventData*)userData; GCHandle[] rgGCHandle = new GCHandle[refObjIndex]; for (int i = 0; i < refObjIndex; ++i) { // below we still use "fixed" to avoid taking dependency on the offset of the first field // in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject) rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned); if (dataRefObj[i] is string) { fixed (char* p = (string)dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } else { fixed (byte* p = (byte[])dataRefObj[i]) userDataPtr[refObjPosition[i]].Ptr = (ulong)p; } } status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData); for (int i = 0; i < refObjIndex; ++i) { rgGCHandle[i].Free(); } } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="activityID"> /// A pointer to the activity ID to log /// </param> /// <param name="childActivityID"> /// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity /// This can be null for events that do not generate a child activity. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" /> // </SecurityKernel> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data) { if (childActivityID != null) { // activity transfers are supported only for events that specify the Send or Receive opcode Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Start || (EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop); } int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")] [System.Security.SecurityCritical] internal unsafe bool WriteEventRaw( ref EventDescriptor eventDescriptor, Guid* activityID, Guid* relatedActivityID, int dataCount, IntPtr data) { int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper( m_regHandle, ref eventDescriptor, activityID, relatedActivityID, dataCount, (EventData*)data); if (status != 0) { SetLastError(status); return false; } return true; } // These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work // either with Manifest ETW or Classic ETW (if Manifest based ETW is not available). [SecurityCritical] private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback) { m_providerId = providerId; m_etwCallback = enableCallback; return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle); } [SecurityCritical] private uint EventUnregister() { uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle); m_regHandle = 0; return status; } static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; private static int bitcount(uint n) { int count = 0; for (; n != 0; n = n >> 4) count += nibblebits[n & 0x0f]; return count; } private static int bitindex(uint n) { Contract.Assert(bitcount(n) == 1); int idx = 0; while ((n & (1 << idx)) == 0) idx++; return idx; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Umbraco.Core.Auditing; using Umbraco.Core.Events; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { /// <summary> /// Represents the Macro Service, which is an easy access to operations involving <see cref="IMacro"/> /// </summary> public class MacroService : IMacroService { private readonly RepositoryFactory _repositoryFactory; private readonly IDatabaseUnitOfWorkProvider _uowProvider; public MacroService() : this(new PetaPocoUnitOfWorkProvider(), new RepositoryFactory()) { } public MacroService(IDatabaseUnitOfWorkProvider provider) : this(provider, new RepositoryFactory()) { } public MacroService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory) { _uowProvider = provider; _repositoryFactory = repositoryFactory; } /// <summary> /// Returns an enum <see cref="MacroTypes"/> based on the properties on the Macro /// </summary> /// <returns><see cref="MacroTypes"/></returns> internal static MacroTypes GetMacroType(IMacro macro) { if (string.IsNullOrEmpty(macro.XsltPath) == false) return MacroTypes.Xslt; if (string.IsNullOrEmpty(macro.ScriptPath) == false) { //we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is //a partial view macro, not a script macro //we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view. return (macro.ScriptPath.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/") || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase))) ? MacroTypes.PartialView : MacroTypes.Script; } if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx")) return MacroTypes.UserControl; if (string.IsNullOrEmpty(macro.ControlType) == false && string.IsNullOrEmpty(macro.ControlAssembly) == false) return MacroTypes.CustomControl; return MacroTypes.Unknown; } /// <summary> /// Gets an <see cref="IMacro"/> object by its alias /// </summary> /// <param name="alias">Alias to retrieve an <see cref="IMacro"/> for</param> /// <returns>An <see cref="IMacro"/> object</returns> public IMacro GetByAlias(string alias) { using (var repository = _repositoryFactory.CreateMacroRepository(_uowProvider.GetUnitOfWork())) { var q = new Query<IMacro>(); q.Where(macro => macro.Alias == alias); return repository.GetByQuery(q).FirstOrDefault(); } } ///// <summary> ///// Gets a list all available <see cref="IMacro"/> objects ///// </summary> ///// <param name="aliases">Optional array of aliases to limit the results</param> ///// <returns>An enumerable list of <see cref="IMacro"/> objects</returns> //public IEnumerable<IMacro> GetAll(params string[] aliases) //{ // using (var repository = _repositoryFactory.CreateMacroRepository(_uowProvider.GetUnitOfWork())) // { // if (aliases.Any()) // { // return GetAllByAliases(repository, aliases); // } // return repository.GetAll(); // } //} public IEnumerable<IMacro> GetAll(params int[] ids) { using (var repository = _repositoryFactory.CreateMacroRepository(_uowProvider.GetUnitOfWork())) { return repository.GetAll(ids); } } public IMacro GetById(int id) { using (var repository = _repositoryFactory.CreateMacroRepository(_uowProvider.GetUnitOfWork())) { return repository.Get(id); } } //private IEnumerable<IMacro> GetAllByAliases(IMacroRepository repo, IEnumerable<string> aliases) //{ // foreach (var alias in aliases) // { // var q = new Query<IMacro>(); // q.Where(macro => macro.Alias == alias); // yield return repo.GetByQuery(q).FirstOrDefault(); // } //} /// <summary> /// Deletes an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to delete</param> /// <param name="userId">Optional id of the user deleting the macro</param> public void Delete(IMacro macro, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMacro>(macro), this)) return; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMacroRepository(uow)) { repository.Delete(macro); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IMacro>(macro, false), this); } Audit.Add(AuditTypes.Delete, "Delete Macro performed by user", userId, -1); } /// <summary> /// Saves an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to save</param> /// <param name="userId">Optional Id of the user deleting the macro</param> public void Save(IMacro macro, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IMacro>(macro), this)) return; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMacroRepository(uow)) { repository.AddOrUpdate(macro); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IMacro>(macro, false), this); } Audit.Add(AuditTypes.Save, "Save Macro performed by user", userId, -1); } ///// <summary> ///// Gets a list all available <see cref="IMacroPropertyType"/> plugins ///// </summary> ///// <returns>An enumerable list of <see cref="IMacroPropertyType"/> objects</returns> //public IEnumerable<IMacroPropertyType> GetMacroPropertyTypes() //{ // return MacroPropertyTypeResolver.Current.MacroPropertyTypes; //} ///// <summary> ///// Gets an <see cref="IMacroPropertyType"/> by its alias ///// </summary> ///// <param name="alias">Alias to retrieve an <see cref="IMacroPropertyType"/> for</param> ///// <returns>An <see cref="IMacroPropertyType"/> object</returns> //public IMacroPropertyType GetMacroPropertyTypeByAlias(string alias) //{ // return MacroPropertyTypeResolver.Current.MacroPropertyTypes.FirstOrDefault(x => x.Alias == alias); //} #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IMacroService, DeleteEventArgs<IMacro>> Deleted; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IMacroService, SaveEventArgs<IMacro>> Saved; #endregion } }
namespace Microsoft.Protocols.TestSuites.MS_OXORULE { using System; using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; /// <summary> /// ActionBlock struct in RuleAction /// </summary> public class ActionBlock { /// <summary> /// ActionData buffer. It is different base on different ActionType /// </summary> private IActionData actionDataValue; /// <summary> /// Specifies the types of action /// </summary> private ActionType actionType; /// <summary> /// MUST be used in conjunction with specific ActionType that support it, and MUST be zero otherwise /// </summary> private uint actionFlavor; /// <summary> /// Client-defined Flags. The ActionFlags field is used solely by the client, and it is not used by the server but stored only /// </summary> private uint actionFlags; /// <summary> /// Type of COUNT /// </summary> private CountByte countType; /// <summary> /// MUST be the cumulative length (in BYTES) of the subsequent fields in this ActionBlock, this Type is uint, otherwise, its Type is ushort. /// </summary> private object actionLength; /// <summary> /// Initializes a new instance of the ActionBlock class. /// </summary> public ActionBlock() { this.countType = CountByte.TwoBytesCount; } /// <summary> /// Initializes a new instance of the ActionBlock class. /// </summary> /// <param name="countType">The COUNT Type of this class.</param> public ActionBlock(CountByte countType) { this.countType = countType; } /// <summary> /// Gets or sets actionData buffer, it is different base on different ActionType /// </summary> public IActionData ActionDataValue { get { return this.actionDataValue; } set { this.actionDataValue = value; } } /// <summary> /// Gets or sets the types of action /// </summary> public ActionType ActionType { get { return this.actionType; } set { this.actionType = value; } } /// <summary> /// Gets or sets the ActionFlavor /// </summary> public uint ActionFlavor { get { return this.actionFlavor; } set { this.actionFlavor = value; } } /// <summary> /// Gets or sets Client-defined Flags. /// </summary> public uint ActionFlags { get { return this.actionFlags; } set { this.actionFlags = value; } } /// <summary> /// Gets type of Count /// </summary> public CountByte CountType { get { return this.countType; } } /// <summary> /// Gets or sets the action length that MUST be the cumulative length (in BYTES) of the subsequent fields in this ActionBlock. If the countType is FourBytesCount, its type is uint. Otherwise, its Type is ushort. /// </summary> public object ActionLength { get { return this.actionLength; } set { if (this.CountType == CountByte.TwoBytesCount) { if (value is int) { this.actionLength = (ushort)(int)value; } else { this.actionLength = (ushort)value; } } else { if (value is int) { this.actionLength = (uint)(int)value; } else { this.actionLength = (uint)value; } } } } /// <summary> /// Get the total Size of ActionData /// </summary> /// <returns>The Size of ActionData buffer.</returns> public int Size() { return this.Serialize().Length; } /// <summary> /// Get serialized byte array for this struct /// </summary> /// <returns>Serialized byte array.</returns> public byte[] Serialize() { List<byte> result = new List<byte>(); if (this.CountType == CountByte.TwoBytesCount) { result.AddRange(BitConverter.GetBytes((ushort)this.ActionLength)); } else if (this.CountType == CountByte.FourBytesCount) { result.AddRange(BitConverter.GetBytes((uint)this.ActionLength)); } result.Add((byte)this.ActionType); result.AddRange(BitConverter.GetBytes(this.ActionFlavor)); result.AddRange(BitConverter.GetBytes(this.ActionFlags)); if (this.ActionDataValue.Serialize() != null) { result.AddRange(this.ActionDataValue.Serialize()); } return result.ToArray(); } /// <summary> /// Deserialized byte array to an ActionBlock instance /// </summary> /// <param name="buffer">Byte array contain data of an ActionBlock instance.</param> /// <returns>Bytes count that deserialized in buffer.</returns> public uint Deserialize(byte[] buffer) { BufferReader bufferReader = new BufferReader(buffer); uint totalBytes = 0; if (this.CountType == CountByte.TwoBytesCount) { this.ActionLength = bufferReader.ReadUInt16(); totalBytes += bufferReader.Position; bufferReader = new BufferReader(bufferReader.ReadBytes((ushort)this.ActionLength)); } else if (this.CountType == CountByte.FourBytesCount) { this.ActionLength = bufferReader.ReadUInt32(); totalBytes += bufferReader.Position; bufferReader = new BufferReader(bufferReader.ReadBytes((uint)this.ActionLength)); } this.ActionType = (ActionType)bufferReader.ReadByte(); this.ActionFlavor = bufferReader.ReadUInt32(); this.ActionFlags = bufferReader.ReadUInt32(); totalBytes += bufferReader.Position; byte[] tmpArray = null; byte[] remainBuffer = bufferReader.ReadToEnd(); tmpArray = remainBuffer; switch (this.ActionType) { case ActionType.OP_MOVE: case ActionType.OP_COPY: // On Exchange 2013, a redundant "0xff" field may be inserted before the actual Action data. if (remainBuffer != null && remainBuffer[0] == 0xff) { tmpArray = new byte[remainBuffer.Length - 1]; Array.Copy(remainBuffer, 1, tmpArray, 0, remainBuffer.Length - 1); this.ActionLength = (ushort)this.ActionLength - 1; } if (this.CountType == CountByte.TwoBytesCount) { this.ActionDataValue = new MoveCopyActionData(); } else if (this.CountType == CountByte.FourBytesCount) { this.ActionDataValue = new MoveCopyActionDataOfExtendedRule(); } break; case ActionType.OP_REPLY: case ActionType.OP_OOF_REPLY: if (this.CountType == CountByte.TwoBytesCount) { this.ActionDataValue = new ReplyActionData(); } else if (this.CountType == CountByte.FourBytesCount) { this.ActionDataValue = new ReplyActionDataOfExtendedRule(); } break; case ActionType.OP_DEFER_ACTION: this.ActionDataValue = new DeferredActionData(); break; case ActionType.OP_BOUNCE: this.ActionDataValue = new BounceActionData(); break; case ActionType.OP_FORWARD: case ActionType.OP_DELEGATE: this.ActionDataValue = new ForwardDelegateActionData(this.CountType); break; case ActionType.OP_TAG: this.ActionDataValue = new TagActionData(); break; case ActionType.OP_DELETE: case ActionType.OP_MARK_AS_READ: this.ActionDataValue = new DeleteMarkReadActionData(); break; } totalBytes += this.ActionDataValue.Deserialize(tmpArray); return totalBytes; } } }
// *********************************************************************** // Copyright (c) 2011-2021 Charlie Poole, Terje Sandstrom // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using NSubstitute; using NUnit.Framework; using NUnit.VisualStudio.TestAdapter.Dump; using NUnit.VisualStudio.TestAdapter.NUnitEngine; namespace NUnit.VisualStudio.TestAdapter.Tests { using Fakes; [Category("TestConverter")] public class TestConverterTests { private NUnitDiscoveryTestCase fakeTestNode; private TestConverter testConverter; [SetUp] public void SetUp() { var xDoc = XDocument.Parse(FakeTestData.TestXml); var parent = Substitute.For<INUnitDiscoveryCanHaveTestFixture>(); parent.Parent.Returns(null as INUnitDiscoverySuiteBase); var className = xDoc.Root.Attribute("classname").Value; var tf = DiscoveryConverter.ExtractTestFixture(parent, xDoc.Root, className); var tcs = DiscoveryConverter.ExtractTestCases(tf, xDoc.Root); Assert.That(tcs.Count(), Is.EqualTo(1), "Setup: More than one test case in fake data"); fakeTestNode = tcs.Single(); var settings = Substitute.For<IAdapterSettings>(); settings.ConsoleOut.Returns(0); settings.UseTestNameInConsoleOutput.Returns(false); settings.CollectSourceInformation.Returns(true); var discoveryConverter = Substitute.For<IDiscoveryConverter>(); testConverter = new TestConverter(new TestLogger(new MessageLoggerStub()), FakeTestData.AssemblyPath, settings, discoveryConverter); } [TearDown] public void TearDown() { testConverter?.Dispose(); } [Test] public void CanMakeTestCaseFromTest() { var testCase = testConverter.ConvertTestCase(fakeTestNode); CheckTestCase(testCase); } [Test] public void CanMakeTestCaseFromTestWithCache() { var testCase = testConverter.ConvertTestCase(fakeTestNode); CheckTestCase(testCase); Assert.That(testConverter.TraitsCache.Keys.Count, Is.EqualTo(1)); Assert.That(testConverter.TraitsCache["121"].Traits.Count, Is.EqualTo(1)); var parentTrait = testConverter.TraitsCache["121"].Traits; Assert.That(parentTrait[0].Name, Is.EqualTo("Category")); Assert.That(parentTrait[0].Value, Is.EqualTo("super")); } [Ignore("To do")] [Test] public void CanMakeTestCaseShouldBuildTraitsCache() { var xmlNodeList = FakeTestData.GetTestNodes(); var tf = Substitute.For<INUnitDiscoveryCanHaveTestCases>(); foreach (XmlNode node in xmlNodeList) { var xElem = XElement.Load(node.CreateNavigator().ReadSubtree()); var tc = DiscoveryConverter.ExtractTestCase(tf, xElem); var testCase = testConverter.ConvertTestCase(tc); } var traitsCache = testConverter.TraitsCache; Assert.Multiple(() => { // There are 12 ids in the TestXml2, but will be storing only ancestor properties. // Not the leaf node test-case properties. Assert.That(traitsCache.Keys.Count, Is.EqualTo(7)); // Even though ancestor doesn't have any properties. Will be storing their ids. // So that we will not make call SelectNodes call again. CheckNodesWithNoProperties(traitsCache); // Will not be storing leaf nodes test-case nodes in the cache. CheckNoTestCaseNodesExist(traitsCache); // Checking assembly level attribute. CheckNodeProperties(traitsCache, "0-1009", new[] { new KeyValuePair<string, string>("Category", "AsmCat") }); // Checking Class level attributes base class & dervied class CheckNodeProperties(traitsCache, "0-1000", new[] { new KeyValuePair<string, string>("Category", "BaseClass") }); CheckNodeProperties(traitsCache, "0-1002", new[] { new KeyValuePair<string, string>("Category", "DerivedClass"), new KeyValuePair<string, string>("Category", "BaseClass") }); // Checking Nested class attributes. CheckNodeProperties(traitsCache, "0-1005", new[] { new KeyValuePair<string, string>("Category", "NS1") }); CheckNodeProperties(traitsCache, "0-1007", new[] { new KeyValuePair<string, string>("Category", "NS2") }); }); } [Test] public void ConvertedTestCaseIsCached() { testConverter.ConvertTestCase(fakeTestNode); var testCase = testConverter.GetCachedTestCase("123"); CheckTestCase(testCase); } [Test] public void CannotMakeTestResultWhenTestCaseIsNotInCache() { var fakeResultNode = new NUnitTestEventTestCase(FakeTestData.GetResultNode()); var results = testConverter.GetVsTestResults(fakeResultNode, Enumerable.Empty<INUnitTestEventTestOutput>().ToList()); Assert.That(results.TestResults.Count, Is.EqualTo(0)); } [Test] public void CanMakeTestResultFromNUnitTestResult() { // This should put the TestCase in the cache var cachedTestCase = testConverter.ConvertTestCase(fakeTestNode); var fakeResultNode = new NUnitTestEventTestCase(FakeTestData.GetResultNode()); var testResults = testConverter.GetVsTestResults(fakeResultNode, Enumerable.Empty<INUnitTestEventTestOutput>().ToList()); var testResult = testResults.TestResults[0]; var testCase = testResult.TestCase; Assert.That(testCase, Is.SameAs(cachedTestCase)); CheckTestCase(testCase); Assert.That(testResult.Outcome, Is.EqualTo(TestOutcome.Passed)); Assert.That(testResult.ErrorMessage, Is.EqualTo(null)); Assert.That(testResult.Duration, Is.EqualTo(TimeSpan.FromSeconds(1.234))); } [TestCase( "<test-output stream=\"Error\" testid=\"0-1001\" testname=\"UnitTests.Test1\"><![CDATA[some stdErr]]></test-output>", "StdErrMsgs:some stdErr")] [TestCase( "<test-output stream=\"Progress\" testid=\"0-1001\" testname=\"UnitTests.Test1\"><![CDATA[some text]]></test-output>", "")] [TestCase( "<test-output stream=\"Error\" testid=\"0-1001\" testname=\"UnitTests.Test1\"><![CDATA[some stdErr]]></test-output>" + ";<test-output stream=\"Progress\" testid=\"0-1001\" testname=\"UnitTests.Test1\"><![CDATA[some text]]></test-output>", "StdErrMsgs:some stdErr")] public void CanMakeTestResultFromNUnitTestResult2(string output, string expectedMessages) { var cachedTestCase = testConverter.ConvertTestCase(fakeTestNode); var fakeResultNode = new NUnitTestEventTestCase(FakeTestData.GetResultNode()); var outputNodes = output.Split(';').Select(i => new NUnitTestEventTestOutput(XmlHelper.CreateXmlNode(i.Trim()))).ToList(); var outputNodesCollection = new List<INUnitTestEventTestOutput>(outputNodes); var testResults = testConverter.GetVsTestResults(fakeResultNode, outputNodesCollection); var testResult = testResults.TestResults[0]; var actualMessages = string.Join(";", testResult.Messages.Select(i => i.Category + ":" + i.Text)); Assert.That(actualMessages, Is.EqualTo(expectedMessages)); } #region Attachment tests [Test] public void Attachments_CorrectAmountOfConvertedAttachments() { var cachedTestCase = testConverter.ConvertTestCase(fakeTestNode); var fakeResultNode = new NUnitTestEventTestCase(FakeTestData.GetResultNode()); var testResults = testConverter.GetVsTestResults(fakeResultNode, Enumerable.Empty<INUnitTestEventTestOutput>().ToList()); var fakeAttachments = fakeResultNode.NUnitAttachments .Where(n => !string.IsNullOrEmpty(n.FilePath)) .ToArray(); TestContext.Out.WriteLine("Incoming attachments"); foreach (var attachment in fakeAttachments) { TestContext.Out.WriteLine($"{attachment.FilePath}"); } var convertedAttachments = testResults.TestResults .SelectMany(tr => tr.Attachments.SelectMany(ats => ats.Attachments)) .ToArray(); TestContext.Out.WriteLine("\nConverted attachments (Uri, path)"); foreach (var attachment in convertedAttachments) { TestContext.Out.WriteLine($"{attachment.Uri.AbsoluteUri} : {attachment.Uri.LocalPath}"); } Assert.Multiple(() => { Assert.That(convertedAttachments.Length, Is.GreaterThan(0), "Some converted attachments were expected"); Assert.That(convertedAttachments.Length, Is.EqualTo(fakeAttachments.Length), "Attachments are not converted"); }); } #endregion Attachment tests private void CheckTestCase(TestCase testCase) { Assert.That(testCase.FullyQualifiedName, Is.EqualTo(FakeTestData.FullyQualifiedName)); Assert.That(testCase.DisplayName, Is.EqualTo(FakeTestData.DisplayName)); Assert.That(testCase.Source, Is.SamePath(FakeTestData.AssemblyPath)); if (testCase.CodeFilePath != null) // Unavailable if not running under VS { Assert.That(testCase.CodeFilePath, Is.SamePath(FakeTestData.CodeFile)); Assert.That(testCase.LineNumber, Is.EqualTo(FakeTestData.LineNumber)); } var traitList = testCase.GetTraits().Select(trait => trait.Name + ":" + trait.Value).ToList(); Assert.That(traitList, Is.EquivalentTo(new[] { "Priority:medium" })); Assert.That(testCase.GetCategories(), Is.EquivalentTo(new[] { "super", "cat1", })); } private void CheckNodesWithNoProperties(IDictionary<string, TraitsFeature.CachedTestCaseInfo> cache) { Assert.That(cache["2"].Traits.Count, Is.EqualTo(0)); Assert.That(cache["0-1010"].Traits.Count, Is.EqualTo(0)); } private void CheckNoTestCaseNodesExist(IDictionary<string, TraitsFeature.CachedTestCaseInfo> cache) { Assert.That(!cache.ContainsKey("0-1008")); Assert.That(!cache.ContainsKey("0-1006")); Assert.That(!cache.ContainsKey("0-1004")); Assert.That(!cache.ContainsKey("0-1003")); Assert.That(!cache.ContainsKey("0-1001")); } private void CheckNodeProperties(IDictionary<string, TraitsFeature.CachedTestCaseInfo> cache, string id, KeyValuePair<string, string>[] kps) { Assert.That(cache.ContainsKey(id)); Assert.That(cache[id].Traits.Count, Is.EqualTo(kps.Count())); var info = cache[id]; foreach (var kp in kps) { Assert.That(info.Traits.Any(t => t.Name == kp.Key && t.Value == kp.Value)); } } [Description("Third-party runners may opt to depend on this. https://github.com/nunit/nunit3-vs-adapter/issues/487#issuecomment-389222879")] [TestCase("NonExplicitParent.ExplicitTest")] [TestCase("ExplicitParent.NonExplicitTest")] public static void NUnitExplicitBoolPropertyIsProvidedForThirdPartyRunnersInExplicitTestCases(string testName) { var testCase = GetSampleTestCase(testName); var property = testCase.Properties.Single(p => p.Id == "NUnit.Explicit" && p.GetValueType() == typeof(bool)); Assert.That(testCase.GetPropertyValue(property), Is.True); } [TestCase("NonExplicitParent.NonExplicitTestWithExplicitCategory")] public static void NUnitExplicitBoolPropertyIsNotProvidedForThirdPartyRunnersInNonExplicitTestCases(string testName) { var testCase = GetSampleTestCase(testName); Assert.That(testCase, Has.Property("Properties").With.None.With.Property("Id").EqualTo("NUnit.Explicit")); } private static TestCase GetSampleTestCase(string fullyQualifiedName) { return TestCaseUtils.ConvertTestCases(@" <test-suite id='1' name='NonExplicitParent' fullname='NonExplicitParent'> <test-case id='2' name='NonExplicitTest' fullname='NonExplicitParent.NonExplicitTestWithExplicitCategory'> <properties> <property name='Category' value='Explicit' /> </properties> </test-case> <test-case id='3' name='ExplicitTest' fullname='NonExplicitParent.ExplicitTest' runstate='Explicit' /> </test-suite> <test-suite id='4' name='ExplicitParent' fullname='ExplicitParent' runstate='Explicit'> <test-case id='5' name='NonExplicitTest' fullname='ExplicitParent.NonExplicitTest' /> </test-suite>").Single(t => t.FullyQualifiedName == fullyQualifiedName); } } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Worker; using Moq; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker { public sealed class StepsRunnerL0 { private Mock<IExecutionContext> _ec; private StepsRunner _stepsRunner; private Variables _variables; private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { var hc = new TestHostContext(this, testName); List<string> warnings; _variables = new Variables( hostContext: hc, copy: new Dictionary<string, string>(), maskHints: new List<MaskHint>(), warnings: out warnings); _ec = new Mock<IExecutionContext>(); _ec.SetupAllProperties(); _ec.Setup(x => x.Variables).Returns(_variables); _stepsRunner = new StepsRunner(); _stepsRunner.Initialize(hc); return hc; } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunsAfterContinueOnError() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded, continueOnError: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded, critical: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded, isFinally: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded, continueOnError: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded, critical: true) }, new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded, isFinally: true) }, }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Select(x => x.Object).ToList()); // Assert. Assert.Equal(TaskResult.SucceededWithIssues, _ec.Object.Result); Assert.Equal(2, variableSet.Length); variableSet[0].Verify(x => x.RunAsync()); variableSet[1].Verify(x => x.RunAsync()); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunsAlwaysRuns() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new { Steps = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, Expected = TaskResult.Succeeded, }, new { Steps = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, Expected = TaskResult.Failed, }, }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Steps.Select(x => x.Object).ToList()); // Assert. Assert.Equal(variableSet.Expected, _ec.Object.Result ?? TaskResult.Succeeded); Assert.Equal(2, variableSet.Steps.Length); variableSet.Steps[0].Verify(x => x.RunAsync()); variableSet.Steps[1].Verify(x => x.RunAsync()); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task RunsFinally() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new { Steps = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.Succeeded, isFinally: true) }, Expected = TaskResult.Succeeded, }, new { Steps = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, isFinally: true) }, Expected = TaskResult.Failed, }, new { Steps = new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, isFinally: true) }, Expected = TaskResult.Failed, }, }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Steps.Select(x => x.Object).ToList()); // Assert. Assert.Equal(variableSet.Expected, _ec.Object.Result ?? TaskResult.Succeeded); Assert.Equal(2, variableSet.Steps.Length); variableSet.Steps[0].Verify(x => x.RunAsync()); variableSet.Steps[1].Verify(x => x.RunAsync()); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task SetsJobResultCorrectly() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new { Steps = new[] { CreateStep(TaskResult.Abandoned) }, Expected = TaskResult.Succeeded }, new { Steps = new[] { CreateStep(TaskResult.Canceled) }, Expected = TaskResult.Succeeded }, new { Steps = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded) }, Expected = TaskResult.Failed }, new { Steps = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, Expected = TaskResult.Failed }, new { Steps = new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, isFinally: true) }, Expected = TaskResult.Failed }, new { Steps = new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Failed) }, Expected = TaskResult.Failed }, new { Steps = new[] { CreateStep(TaskResult.Failed, continueOnError: true), CreateStep(TaskResult.Succeeded) }, Expected = TaskResult.SucceededWithIssues }, new { Steps = new[] { CreateStep(TaskResult.Failed, continueOnError: true, critical: true), CreateStep(TaskResult.Succeeded) }, Expected = TaskResult.SucceededWithIssues }, new { Steps = new[] { CreateStep(TaskResult.Skipped) }, Expected = TaskResult.Succeeded }, new { Steps = new[] { CreateStep(TaskResult.Succeeded) }, Expected = TaskResult.Succeeded }, new { Steps = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.Failed) }, Expected = TaskResult.Failed }, new { Steps = new[] { CreateStep(TaskResult.Succeeded), CreateStep(TaskResult.SucceededWithIssues) }, Expected = TaskResult.SucceededWithIssues }, new { Steps = new[] { CreateStep(TaskResult.SucceededWithIssues), CreateStep(TaskResult.Succeeded) }, Expected = TaskResult.SucceededWithIssues }, new { Steps = new[] { CreateStep(TaskResult.SucceededWithIssues), CreateStep(TaskResult.Failed) }, Expected = TaskResult.Failed }, // Abandoned // Canceled // Failed // Skipped // Succeeded // SucceededWithIssues }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Steps.Select(x => x.Object).ToList()); // Assert. Assert.True( variableSet.Expected == (_ec.Object.Result ?? TaskResult.Succeeded), $"Expected '{variableSet.Expected}'. Actual '{_ec.Object.Result}'. Steps: {FormatSteps(variableSet.Steps)}"); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task SkipsAfterCriticalFailure() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, continueOnError: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, critical: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, alwaysRun: true, continueOnError: true, critical: true) }, }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Select(x => x.Object).ToList()); // Assert. Assert.Equal(TaskResult.Failed, _ec.Object.Result); Assert.Equal(2, variableSet.Length); variableSet[0].Verify(x => x.RunAsync()); variableSet[1].Verify(x => x.RunAsync(), Times.Never()); } } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Worker")] public async Task SkipsAfterFailure() { using (TestHostContext hc = CreateTestContext()) { // Arrange. var variableSets = new[] { new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded) }, new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, continueOnError: true) }, new[] { CreateStep(TaskResult.Failed), CreateStep(TaskResult.Succeeded, critical: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, alwaysRun: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, continueOnError: true) }, new[] { CreateStep(TaskResult.Failed, critical: true), CreateStep(TaskResult.Succeeded, critical: true) }, }; foreach (var variableSet in variableSets) { _ec.Object.Result = null; // Act. await _stepsRunner.RunAsync( jobContext: _ec.Object, steps: variableSet.Select(x => x.Object).ToList()); // Assert. Assert.Equal(TaskResult.Failed, _ec.Object.Result); Assert.Equal(2, variableSet.Length); variableSet[0].Verify(x => x.RunAsync()); variableSet[1].Verify(x => x.RunAsync(), Times.Never()); } } } private Mock<IStep> CreateStep(TaskResult result, Boolean alwaysRun = false, Boolean continueOnError = false, Boolean critical = false, Boolean isFinally = false) { // Setup the step. var step = new Mock<IStep>(); step.Setup(x => x.AlwaysRun).Returns(alwaysRun); step.Setup(x => x.ContinueOnError).Returns(continueOnError); step.Setup(x => x.Critical).Returns(critical); step.Setup(x => x.Enabled).Returns(true); step.Setup(x => x.Finally).Returns(isFinally); step.Setup(x => x.RunAsync()).Returns(Task.CompletedTask); // Setup the step execution context. var stepContext = new Mock<IExecutionContext>(); stepContext.SetupAllProperties(); stepContext.Setup(x => x.Variables).Returns(_variables); stepContext.Object.Result = result; step.Setup(x => x.ExecutionContext).Returns(stepContext.Object); return step; } private string FormatSteps(IEnumerable<Mock<IStep>> steps) { return String.Join( " ; ", steps.Select(x => String.Format( CultureInfo.InvariantCulture, "Returns={0},AlwaysRun={1},ContinueOnError={2},Critical={3},Enabled={4},Finally={5}", x.Object.ExecutionContext.Result, x.Object.AlwaysRun, x.Object.ContinueOnError, x.Object.Critical, x.Object.Enabled, x.Object.Finally))); } } }
#define USE_AUTOLAYOUT #define ENABLE_KEYBOARD_AVOIDANCE #define ENABLE_LAYOUT_SUBVIEWS #define ENABLE_WILL_ROTATE_ADJUSTMENT using System; using CoreGraphics; using UIKit; using Foundation; namespace MediaNotes { [Register ("YYCommentContainerView")] public class YYCommentContainerView : UIView { public YYCommentContainerView (IntPtr ptr) : base (ptr) { } [Export ("requiresConstraintBasedLayout")] static bool Requires () { return true; } } public class YYCommentContainerViewController : UIViewController { public YYCommentViewController commentViewController { get; set; } bool commentViewIsVisible; float keyboardOverlap; UIView commentView; bool observersregistered; public UIViewController contentController { get; set; } public YYCommentContainerViewController (UIViewController child) : base () { contentController = child; AddChildViewController (child); child.DidMoveToParentViewController (this); if (child.WantsFullScreenLayout) { WantsFullScreenLayout = true; UIApplication.SharedApplication.SetStatusBarStyle (UIStatusBarStyle.BlackTranslucent, false); } commentViewController = new YYCommentViewController (); commentViewController.associatedObject = (PhotoViewController)child; } public YYCommentViewController YYcommentViewController () { YYCommentViewController controller = commentViewController; if (contentController.Equals (controller.associatedObject)) return controller; else return null; } public override string Title { get { return contentController.Title; } } public override void LoadView () { CGRect rect = UIScreen.MainScreen.Bounds; View = new UIView (rect); commentView = commentViewController.View; commentView.Layer.CornerRadius = 8.0f; commentView.Alpha = 0.0f; contentController.View.Frame = rect; commentView.Bounds = new CGRect (0.0f, 0.0f, rect.Size.Width / 2.0f, rect.Size.Height / 4.0f); View.AddSubview (contentController.View); UILongPressGestureRecognizer gestureRecognizer = new UILongPressGestureRecognizer (this, new ObjCRuntime.Selector ("LongPressGesture:")); View.AddGestureRecognizer (gestureRecognizer); # if USE_AUTOLAYOUT commentView.TranslatesAutoresizingMaskIntoConstraints = false; # endif } public void AdjustCommentviewFrame () { CGRect viewBounds = View.Bounds; float height = (float) viewBounds.Size.Height; float width = (float) viewBounds.Size.Width; CGRect rect = commentView.Frame; rect.Y = (height - commentView.Bounds.Size.Height); rect.X = (width - commentView.Bounds.Size.Width) / 2.0f; commentView.Frame = rect; } public void AdjustCommentViewYPosition (float yOffset, float duration, bool finished) { CGRect rect = commentView.Frame; rect.Y = rect.Y - yOffset; //Check UIView.Animate (duration, () => { commentView.Frame = rect; }); } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { return contentController.ShouldAutorotate (); } public override bool ShouldAutomaticallyForwardAppearanceMethods { get { return false; } } [Export("LongPressGesture:")] void toggleCommentViewVisibility (UIGestureRecognizer gestureRecognizer) { bool began = (gestureRecognizer.State == UIGestureRecognizerState.Began); if (!began) return; if (commentViewIsVisible) { commentViewIsVisible = false; commentViewController.WillMoveToParentViewController (null); commentViewController.BeginAppearanceTransition (false, true); UIView.Animate (0.5f, () => { commentView.Alpha = 0.5f; }, () => { commentView.RemoveFromSuperview (); commentViewController.EndAppearanceTransition (); commentViewController.RemoveFromParentViewController (); }); } else { commentViewIsVisible = true; AddChildViewController (commentViewController); commentViewController.BeginAppearanceTransition (true, true); View.InsertSubviewAbove (commentView, contentController.View); # if (!USE_AUTOLAYOUT) AdjustCommentviewFrame(); # else View.SetNeedsUpdateConstraints (); # endif UIView.Animate (.5, () => { commentView.Alpha = 0.5f;}, () => { commentViewController.EndAppearanceTransition (); commentViewController.DidMoveToParentViewController (this); }); } } # if (!USE_AUTOLAYOUT && ENABLE_LAYOUT_SUBVIEWS) public override void ViewWillLayoutSubviews () { if(commentViewIsVisible) AdjustCommentviewFrame(); } # else // If our content controller has been removed because of a memory warning we need to reinsert if we are appearing. public override void ViewWillLayoutSubviews () { if (contentController.IsViewLoaded == false) { if (commentViewIsVisible) { View.InsertSubviewBelow (contentController.View, commentView); } else { View.AddSubview (contentController.View); } } } # endif # if ENABLE_WILL_ROTATE_ADJUSTMENT public override void WillAnimateRotation (UIInterfaceOrientation toInterfaceOrientation, double duration) { if (commentViewIsVisible) { AdjustCommentviewFrame (); } } # endif # if USE_AUTOLAYOUT public override void UpdateViewConstraints () { if (commentViewIsVisible) { NSLayoutConstraint constraint1 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, View, NSLayoutAttribute.CenterX, 1.0f, 0.0f); NSLayoutConstraint constraint2 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Bottom, NSLayoutRelation.Equal, View, NSLayoutAttribute.Bottom, 1.0f, 0.0f); NSLayoutConstraint constraint3 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, View, NSLayoutAttribute.Width, 0.5f, 0.0f); NSLayoutConstraint constarint4 = NSLayoutConstraint.Create (commentView, NSLayoutAttribute.Height, NSLayoutRelation.Equal, View, NSLayoutAttribute.Height, 0.25f, 0.0f); View.AddConstraints (new NSLayoutConstraint[] { constraint1, constraint2, constraint3, constarint4 }); } base.UpdateViewConstraints (); } # endif public override void ViewWillAppear (bool animated) { contentController.BeginAppearanceTransition (true, true); if (commentViewIsVisible) { commentViewController.BeginAppearanceTransition (true, true); } } public override void ViewWillDisappear (bool animated) { contentController.BeginAppearanceTransition (false, false); if (commentViewIsVisible) { commentViewController.BeginAppearanceTransition (false, false); } } public override void ViewDidAppear (bool animated) { contentController.EndAppearanceTransition (); if (commentViewIsVisible) { commentViewController.EndAppearanceTransition (); } # if ENABLE_KEYBOARD_AVOIDANCE if (observersregistered == false) { NSNotificationCenter.DefaultCenter.AddObserver (this, new ObjCRuntime.Selector ("KeyBoardWillShow"), UIKeyboard.WillShowNotification, null); NSNotificationCenter.DefaultCenter.AddObserver (this, new ObjCRuntime.Selector ("KeyBoardWillHide"), UIKeyboard.WillHideNotification, null); } # endif } public override void ViewDidDisappear (bool animated) { contentController.EndAppearanceTransition (); if (commentViewIsVisible) { commentViewController.EndAppearanceTransition (); } # if ENABLE_KEYBOARD_AVOIDANCE NSNotificationCenter.DefaultCenter.RemoveObserver (this); observersregistered = false; # endif } # if ENABLE_KEYBOARD_AVOIDANCE [Export("KeyBoardWillShow:")] public void KeyboardWillShow (NSNotification notification) { //Gather some info about the keyboard and its information CGRect keyboardEndFrame = CGRect.Empty; float animationDuration = 0.0f; notification.UserInfo.ObjectForKey (UIKeyboard.FrameEndUserInfoKey); //GetValues notification.UserInfo.ObjectForKey (UIKeyboard.AnimationDurationUserInfoKey); //GetValues keyboardEndFrame = View.ConvertRectFromView (keyboardEndFrame, null); keyboardOverlap = (float) keyboardEndFrame.Size.Height; AdjustCommentViewYPosition (keyboardOverlap, animationDuration, false); } [Export("KeyBoardWillHide:")] public void KeyBoardWillHide (NSNotification notification) { //Gather some info about the keyboard and its information float animationDuration = 0.0f; notification.UserInfo.ObjectForKey (UIKeyboard.AnimationDurationUserInfoKey); AdjustCommentViewYPosition (-1.0f * keyboardOverlap, animationDuration, false); keyboardOverlap = 0; } # endif } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Xml.XPath; using Examine; using Examine.LuceneEngine.SearchCriteria; using Examine.Providers; using Lucene.Net.Documents; using Umbraco.Core; using Umbraco.Core.Dynamics; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Xml; using Umbraco.Web.Models; using UmbracoExamine; using umbraco; using umbraco.cms.businesslogic; using ContentType = umbraco.cms.businesslogic.ContentType; namespace Umbraco.Web.PublishedCache.XmlPublishedCache { /// <summary> /// An IPublishedMediaStore that first checks for the media in Examine, and then reverts to the database /// </summary> /// <remarks> /// NOTE: In the future if we want to properly cache all media this class can be extended or replaced when these classes/interfaces are exposed publicly. /// </remarks> internal class PublishedMediaCache : IPublishedMediaCache { public PublishedMediaCache() { } /// <summary> /// Generally used for unit testing to use an explicit examine searcher /// </summary> /// <param name="searchProvider"></param> /// <param name="indexProvider"></param> internal PublishedMediaCache(BaseSearchProvider searchProvider, BaseIndexProvider indexProvider) { _searchProvider = searchProvider; _indexProvider = indexProvider; } private readonly BaseSearchProvider _searchProvider; private readonly BaseIndexProvider _indexProvider; public virtual IPublishedContent GetById(UmbracoContext umbracoContext, bool preview, int nodeId) { return GetUmbracoMedia(nodeId); } public virtual IEnumerable<IPublishedContent> GetAtRoot(UmbracoContext umbracoContext, bool preview) { var rootMedia = global::umbraco.cms.businesslogic.media.Media.GetRootMedias(); var result = new List<IPublishedContent>(); //TODO: need to get a ConvertFromMedia method but we'll just use this for now. foreach (var media in rootMedia .Select(m => global::umbraco.library.GetMedia(m.Id, true)) .Where(media => media != null && media.Current != null)) { media.MoveNext(); result.Add(ConvertFromXPathNavigator(media.Current)); } return result; } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IPublishedContent GetSingleByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, string xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual IEnumerable<IPublishedContent> GetByXPath(UmbracoContext umbracoContext, bool preview, XPathExpression xpath, XPathVariable[] vars) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual XPathNavigator GetXPathNavigator(UmbracoContext umbracoContext, bool preview) { throw new NotImplementedException("PublishedMediaCache does not support XPath."); } public virtual bool HasContent(UmbracoContext context, bool preview) { throw new NotImplementedException(); } private ExamineManager GetExamineManagerSafe() { try { return ExamineManager.Instance; } catch (TypeInitializationException) { return null; } } private BaseIndexProvider GetIndexProviderSafe() { if (_indexProvider != null) return _indexProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.IndexProviderCollection["InternalIndexer"]; } catch (Exception ex) { LogHelper.Error<PublishedMediaCache>("Could not retreive the InternalIndexer", ex); //something didn't work, continue returning null. } } return null; } private BaseSearchProvider GetSearchProviderSafe() { if (_searchProvider != null) return _searchProvider; var eMgr = GetExamineManagerSafe(); if (eMgr != null) { try { //by default use the InternalSearcher return eMgr.SearchProviderCollection["InternalSearcher"]; } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } } return null; } private IPublishedContent GetUmbracoMedia(int id) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.Id(id).Not().Field(UmbracoContentIndexer.IndexPathFieldName, "-1,-21,".MultipleCharacterWildcard()); //the above filter will create a query like this, NOTE: That since the use of the wildcard, it automatically escapes it in Lucene. //+(+__NodeId:3113 -__Path:-1,-21,*) +__IndexType:media var results = searchProvider.Search(filter.Compile()); if (results.Any()) { return ConvertFromSearchResult(results.First()); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia //TODO: Need to fix examine in LB scenarios! } } var media = global::umbraco.library.GetMedia(id, true); if (media != null && media.Current != null) { media.MoveNext(); var moved = media.Current.MoveToFirstChild(); //first check if we have an error if (moved) { if (media.Current.Name.InvariantEquals("error")) { return null; } } if (moved) { //move back to the parent and return media.Current.MoveToParent(); } return ConvertFromXPathNavigator(media.Current); } return null; } internal IPublishedContent ConvertFromSearchResult(SearchResult searchResult) { //NOTE: Some fields will not be included if the config section for the internal index has been //mucked around with. It should index everything and so the index definition should simply be: // <IndexSet SetName="InternalIndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/Internal/" /> var values = new Dictionary<string, string>(searchResult.Fields); //we need to ensure some fields exist, because of the above issue if (!new []{"template", "templateId"}.Any(values.ContainsKey)) values.Add("template", 0.ToString()); if (!new[] { "sortOrder" }.Any(values.ContainsKey)) values.Add("sortOrder", 0.ToString()); if (!new[] { "urlName" }.Any(values.ContainsKey)) values.Add("urlName", ""); if (!new[] { "nodeType" }.Any(values.ContainsKey)) values.Add("nodeType", 0.ToString()); if (!new[] { "creatorName" }.Any(values.ContainsKey)) values.Add("creatorName", ""); if (!new[] { "writerID" }.Any(values.ContainsKey)) values.Add("writerID", 0.ToString()); if (!new[] { "creatorID" }.Any(values.ContainsKey)) values.Add("creatorID", 0.ToString()); if (!new[] { "createDate" }.Any(values.ContainsKey)) values.Add("createDate", default(DateTime).ToString("yyyy-MM-dd HH:mm:ss")); if (!new[] { "level" }.Any(values.ContainsKey)) { values.Add("level", values["__Path"].Split(',').Length.ToString()); } return new DictionaryPublishedContent(values, d => d.ParentId != -1 //parent should be null if -1 ? GetUmbracoMedia(d.ParentId) : null, //callback to return the children of the current node d => GetChildrenMedia(d.Id), GetProperty, true); } internal IPublishedContent ConvertFromXPathNavigator(XPathNavigator xpath) { if (xpath == null) throw new ArgumentNullException("xpath"); var values = new Dictionary<string, string> {{"nodeName", xpath.GetAttribute("nodeName", "")}}; if (!UmbracoSettings.UseLegacyXmlSchema) { values.Add("nodeTypeAlias", xpath.Name); } var result = xpath.SelectChildren(XPathNodeType.Element); //add the attributes e.g. id, parentId etc if (result.Current != null && result.Current.HasAttributes) { if (result.Current.MoveToFirstAttribute()) { //checking for duplicate keys because of the 'nodeTypeAlias' might already be added above. if (!values.ContainsKey(result.Current.Name)) { values.Add(result.Current.Name, result.Current.Value); } while (result.Current.MoveToNextAttribute()) { if (!values.ContainsKey(result.Current.Name)) { values.Add(result.Current.Name, result.Current.Value); } } result.Current.MoveToParent(); } } //add the user props while (result.MoveNext()) { if (result.Current != null && !result.Current.HasAttributes) { string value = result.Current.Value; if (string.IsNullOrEmpty(value)) { if (result.Current.HasAttributes || result.Current.SelectChildren(XPathNodeType.Element).Count > 0) { value = result.Current.OuterXml; } } values.Add(result.Current.Name, value); } } return new DictionaryPublishedContent(values, d => d.ParentId != -1 //parent should be null if -1 ? GetUmbracoMedia(d.ParentId) : null, //callback to return the children of the current node based on the xml structure already found d => GetChildrenMedia(d.Id, xpath), GetProperty, false); } /// <summary> /// We will need to first check if the document was loaded by Examine, if so we'll need to check if this property exists /// in the results, if it does not, then we'll have to revert to looking up in the db. /// </summary> /// <param name="dd"> </param> /// <param name="alias"></param> /// <returns></returns> private IPublishedContentProperty GetProperty(DictionaryPublishedContent dd, string alias) { if (dd.LoadedFromExamine) { //if this is from Examine, lets check if the alias does not exist on the document if (dd.Properties.All(x => x.Alias != alias)) { //ok it doesn't exist, we might assume now that Examine didn't index this property because the index is not set up correctly //so before we go loading this from the database, we can check if the alias exists on the content type at all, this information //is cached so will be quicker to look up. if (dd.Properties.Any(x => x.Alias == UmbracoContentIndexer.NodeTypeAliasFieldName)) { var aliasesAndNames = ContentType.GetAliasesAndNames(dd.Properties.First(x => x.Alias.InvariantEquals(UmbracoContentIndexer.NodeTypeAliasFieldName)).Value.ToString()); if (aliasesAndNames != null) { if (!aliasesAndNames.ContainsKey(alias)) { //Ok, now we know it doesn't exist on this content type anyways return null; } } } //if we've made it here, that means it does exist on the content type but not in examine, we'll need to query the db :( var media = global::umbraco.library.GetMedia(dd.Id, true); if (media != null && media.Current != null) { media.MoveNext(); var mediaDoc = ConvertFromXPathNavigator(media.Current); return mediaDoc.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); } } } //We've made it here which means that the value is stored in the Examine index. //We are going to check for a special field however, that is because in some cases we store a 'Raw' //value in the index such as for xml/html. var rawValue = dd.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(UmbracoContentIndexer.RawFieldPrefix + alias)); return rawValue ?? dd.Properties.FirstOrDefault(x => x.Alias.InvariantEquals(alias)); } /// <summary> /// A Helper methods to return the children for media whther it is based on examine or xml /// </summary> /// <param name="parentId"></param> /// <param name="xpath"></param> /// <returns></returns> private IEnumerable<IPublishedContent> GetChildrenMedia(int parentId, XPathNavigator xpath = null) { //if there is no navigator, try examine first, then re-look it up if (xpath == null) { var searchProvider = GetSearchProviderSafe(); if (searchProvider != null) { try { //first check in Examine as this is WAY faster var criteria = searchProvider.CreateSearchCriteria("media"); var filter = criteria.ParentId(parentId); ISearchResults results; //we want to check if the indexer for this searcher has "sortOrder" flagged as sortable. //if so, we'll use Lucene to do the sorting, if not we'll have to manually sort it (slower). var indexer = GetIndexProviderSafe(); var useLuceneSort = indexer != null && indexer.IndexerData.StandardFields.Any(x => x.Name.InvariantEquals("sortOrder") && x.EnableSorting); if (useLuceneSort) { //we have a sortOrder field declared to be sorted, so we'll use Examine results = searchProvider.Search( filter.And().OrderBy(new SortableField("sortOrder", SortType.Int)).Compile()); } else { results = searchProvider.Search(filter.Compile()); } if (results.Any()) { return useLuceneSort ? results.Select(ConvertFromSearchResult) //will already be sorted by lucene : results.Select(ConvertFromSearchResult).OrderBy(x => x.SortOrder); } else { //if there's no result then return null. Previously we defaulted back to library.GetMedia below //but this will always get called for when we are getting descendents since many items won't have //children and then we are hitting the database again! //So instead we're going to rely on Examine to have the correct results like it should. return Enumerable.Empty<IPublishedContent>(); } } catch (FileNotFoundException) { //Currently examine is throwing FileNotFound exceptions when we have a loadbalanced filestore and a node is published in umbraco //See this thread: http://examine.cdodeplex.com/discussions/264341 //Catch the exception here for the time being, and just fallback to GetMedia } } //falling back to get media var media = library.GetMedia(parentId, true); if (media != null && media.Current != null) { media.MoveNext(); xpath = media.Current; } else { return Enumerable.Empty<IPublishedContent>(); } } //The xpath might be the whole xpath including the current ones ancestors so we need to select the current node var item = xpath.Select("//*[@id='" + parentId + "']"); if (item.Current == null) { return Enumerable.Empty<IPublishedContent>(); } var children = item.Current.SelectChildren(XPathNodeType.Element); var mediaList = new List<IPublishedContent>(); foreach(XPathNavigator x in children) { //NOTE: I'm not sure why this is here, it is from legacy code of ExamineBackedMedia, but // will leave it here as it must have done something! if (x.Name != "contents") { //make sure it's actually a node, not a property if (!string.IsNullOrEmpty(x.GetAttribute("path", "")) && !string.IsNullOrEmpty(x.GetAttribute("id", ""))) { mediaList.Add(ConvertFromXPathNavigator(x)); } } } return mediaList; } /// <summary> /// An IPublishedContent that is represented all by a dictionary. /// </summary> /// <remarks> /// This is a helper class and definitely not intended for public use, it expects that all of the values required /// to create an IPublishedContent exist in the dictionary by specific aliases. /// </remarks> internal class DictionaryPublishedContent : PublishedContentBase { public DictionaryPublishedContent( IDictionary<string, string> valueDictionary, Func<DictionaryPublishedContent, IPublishedContent> getParent, Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> getChildren, Func<DictionaryPublishedContent, string, IPublishedContentProperty> getProperty, bool fromExamine) { if (valueDictionary == null) throw new ArgumentNullException("valueDictionary"); if (getParent == null) throw new ArgumentNullException("getParent"); if (getProperty == null) throw new ArgumentNullException("getProperty"); _getParent = getParent; _getChildren = getChildren; _getProperty = getProperty; LoadedFromExamine = fromExamine; ValidateAndSetProperty(valueDictionary, val => _id = int.Parse(val), "id", "nodeId", "__NodeId"); //should validate the int! ValidateAndSetProperty(valueDictionary, val => _templateId = int.Parse(val), "template", "templateId"); ValidateAndSetProperty(valueDictionary, val => _sortOrder = int.Parse(val), "sortOrder"); ValidateAndSetProperty(valueDictionary, val => _name = val, "nodeName", "__nodeName"); ValidateAndSetProperty(valueDictionary, val => _urlName = val, "urlName"); ValidateAndSetProperty(valueDictionary, val => _documentTypeAlias = val, "nodeTypeAlias", UmbracoContentIndexer.NodeTypeAliasFieldName); ValidateAndSetProperty(valueDictionary, val => _documentTypeId = int.Parse(val), "nodeType"); ValidateAndSetProperty(valueDictionary, val => _writerName = val, "writerName"); ValidateAndSetProperty(valueDictionary, val => _creatorName = val, "creatorName", "writerName"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _writerId = int.Parse(val), "writerID"); ValidateAndSetProperty(valueDictionary, val => _creatorId = int.Parse(val), "creatorID", "writerID"); //this is a bit of a hack fix for: U4-1132 ValidateAndSetProperty(valueDictionary, val => _path = val, "path", "__Path"); ValidateAndSetProperty(valueDictionary, val => _createDate = ParseDateTimeValue(val), "createDate"); ValidateAndSetProperty(valueDictionary, val => _updateDate = ParseDateTimeValue(val), "updateDate"); ValidateAndSetProperty(valueDictionary, val => _level = int.Parse(val), "level"); ValidateAndSetProperty(valueDictionary, val => { int pId; ParentId = -1; if (int.TryParse(val, out pId)) { ParentId = pId; } }, "parentID"); _properties = new Collection<IPublishedContentProperty>(); //loop through remaining values that haven't been applied foreach (var i in valueDictionary.Where(x => !_keysAdded.Contains(x.Key))) { //this is taken from examine _properties.Add(i.Key.InvariantStartsWith("__") ? new PropertyResult(i.Key, i.Value, Guid.Empty, PropertyResultType.CustomProperty) : new PropertyResult(i.Key, i.Value, Guid.Empty, PropertyResultType.UserProperty)); } } private DateTime ParseDateTimeValue(string val) { if (LoadedFromExamine) { try { //we might need to parse the date time using Lucene converters return DateTools.StringToDate(val); } catch (FormatException) { //swallow exception, its not formatted correctly so revert to just trying to parse } } return DateTime.Parse(val); } /// <summary> /// Flag to get/set if this was laoded from examine cache /// </summary> internal bool LoadedFromExamine { get; private set; } private readonly Func<DictionaryPublishedContent, IPublishedContent> _getParent; private readonly Func<DictionaryPublishedContent, IEnumerable<IPublishedContent>> _getChildren; private readonly Func<DictionaryPublishedContent, string, IPublishedContentProperty> _getProperty; /// <summary> /// Returns 'Media' as the item type /// </summary> public override PublishedItemType ItemType { get { return PublishedItemType.Media; } } public override IPublishedContent Parent { get { return _getParent(this); } } public int ParentId { get; private set; } public override int Id { get { return _id; } } public override int TemplateId { get { //TODO: should probably throw a not supported exception since media doesn't actually support this. return _templateId; } } public override int SortOrder { get { return _sortOrder; } } public override string Name { get { return _name; } } public override string UrlName { get { return _urlName; } } public override string DocumentTypeAlias { get { return _documentTypeAlias; } } public override int DocumentTypeId { get { return _documentTypeId; } } public override string WriterName { get { return _writerName; } } public override string CreatorName { get { return _creatorName; } } public override int WriterId { get { return _writerId; } } public override int CreatorId { get { return _creatorId; } } public override string Path { get { return _path; } } public override DateTime CreateDate { get { return _createDate; } } public override DateTime UpdateDate { get { return _updateDate; } } public override Guid Version { get { return _version; } } public override int Level { get { return _level; } } public override ICollection<IPublishedContentProperty> Properties { get { return _properties; } } public override IEnumerable<IPublishedContent> Children { get { return _getChildren(this); } } public override IPublishedContentProperty GetProperty(string alias) { return _getProperty(this, alias); } private readonly List<string> _keysAdded = new List<string>(); private int _id; private int _templateId; private int _sortOrder; private string _name; private string _urlName; private string _documentTypeAlias; private int _documentTypeId; private string _writerName; private string _creatorName; private int _writerId; private int _creatorId; private string _path; private DateTime _createDate; private DateTime _updateDate; private Guid _version; private int _level; private readonly ICollection<IPublishedContentProperty> _properties; private void ValidateAndSetProperty(IDictionary<string, string> valueDictionary, Action<string> setProperty, params string[] potentialKeys) { var key = potentialKeys.FirstOrDefault(x => valueDictionary.ContainsKey(x) && valueDictionary[x] != null); if (key == null) { throw new FormatException("The valueDictionary is not formatted correctly and is missing any of the '" + string.Join(",", potentialKeys) + "' elements"); } setProperty(valueDictionary[key]); _keysAdded.Add(key); } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.UserModel { using System; using System.Collections.Generic; using NPOI.SS.Util; using System.Collections; using NPOI.Util; /// <summary> /// Indicate the position of the margin. One of left, right, top and bottom. /// </summary> public enum MarginType : short { /// <summary> /// referes to the left margin /// </summary> LeftMargin = 0, /// <summary> /// referes to the right margin /// </summary> RightMargin = 1, /// <summary> /// referes to the top margin /// </summary> TopMargin = 2, /// <summary> /// referes to the bottom margin /// </summary> BottomMargin = 3, HeaderMargin = 4, FooterMargin = 5 } /// <summary> /// Define the position of the pane. One of lower/right, upper/right, lower/left and upper/left. /// </summary> public enum PanePosition : byte { /// <summary> /// referes to the lower/right corner /// </summary> LowerRight = 0, /// <summary> /// referes to the upper/right corner /// </summary> UpperRight = 1, /// <summary> /// referes to the lower/left corner /// </summary> LowerLeft = 2, /// <summary> /// referes to the upper/left corner /// </summary> UpperLeft = 3, } /// <summary> /// High level representation of a Excel worksheet. /// </summary> /// <remarks> /// Sheets are the central structures within a workbook, and are where a user does most of his spreadsheet work. /// The most common type of sheet is the worksheet, which is represented as a grid of cells. Worksheet cells can /// contain text, numbers, dates, and formulas. Cells can also be formatted. /// </remarks> public interface ISheet { /// <summary> /// Create a new row within the sheet and return the high level representation /// </summary> /// <param name="rownum">The row number.</param> /// <returns>high level Row object representing a row in the sheet</returns> /// <see>RemoveRow(Row)</see> IRow CreateRow(int rownum); /// <summary> /// Remove a row from this sheet. All cells Contained in the row are Removed as well /// </summary> /// <param name="row">a row to Remove.</param> void RemoveRow(IRow row); /// <summary> /// Returns the logical row (not physical) 0-based. If you ask for a row that is not /// defined you get a null. This is to say row 4 represents the fifth row on a sheet. /// </summary> /// <param name="rownum">row to get (0-based).</param> /// <returns>the rownumber or null if its not defined on the sheet</returns> IRow GetRow(int rownum); /// <summary> /// Returns the number of physically defined rows (NOT the number of rows in the sheet) /// </summary> /// <value>the number of physically defined rows in this sheet.</value> int PhysicalNumberOfRows { get; } /// <summary> /// Gets the first row on the sheet /// </summary> /// <value>the number of the first logical row on the sheet (0-based).</value> int FirstRowNum { get; } /// <summary> /// Gets the last row on the sheet /// </summary> /// <value>last row contained n this sheet (0-based)</value> int LastRowNum { get; } /// <summary> /// whether force formula recalculation. /// </summary> bool ForceFormulaRecalculation { get; set; } /// <summary> /// Get the visibility state for a given column /// </summary> /// <param name="columnIndex">the column to get (0-based)</param> /// <param name="hidden">the visiblity state of the column</param> void SetColumnHidden(int columnIndex, bool hidden); /// <summary> /// Get the hidden state for a given column /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <returns>hidden - <c>false</c> if the column is visible</returns> bool IsColumnHidden(int columnIndex); /// <summary> /// Copy the source row to the target row. If the target row exists, the new copied row will be inserted before the existing one /// </summary> /// <param name="sourceIndex">source index</param> /// <param name="targetIndex">target index</param> /// <returns>the new copied row object</returns> IRow CopyRow(int sourceIndex, int targetIndex); /// <summary> /// Set the width (in units of 1/256th of a character width) /// </summary> /// <param name="columnIndex">the column to set (0-based)</param> /// <param name="width">the width in units of 1/256th of a character width</param> /// <remarks> /// The maximum column width for an individual cell is 255 characters. /// This value represents the number of characters that can be displayed /// in a cell that is formatted with the standard font. /// </remarks> void SetColumnWidth(int columnIndex, int width); /// <summary> /// get the width (in units of 1/256th of a character width ) /// </summary> /// <param name="columnIndex">the column to get (0-based)</param> /// <returns>the width in units of 1/256th of a character width</returns> int GetColumnWidth(int columnIndex); /// <summary> /// get the width in pixel /// </summary> /// <param name="columnIndex"></param> /// <returns></returns> /// <remarks> /// Please note, that this method works correctly only for workbooks /// with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). /// If the default font is changed the column width can be streched /// </remarks> float GetColumnWidthInPixels(int columnIndex); /// <summary> /// Get the default column width for the sheet (if the columns do not define their own width) /// in characters /// </summary> /// <value>default column width measured in characters.</value> int DefaultColumnWidth { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// twips (1/20 of a point) /// </summary> /// <value>default row height measured in twips (1/20 of a point)</value> short DefaultRowHeight { get; set; } /// <summary> /// Get the default row height for the sheet (if the rows do not define their own height) in /// points. /// </summary> /// <value>The default row height in points.</value> float DefaultRowHeightInPoints { get; set; } /// <summary> /// Returns the CellStyle that applies to the given /// (0 based) column, or null if no style has been /// set for that column /// </summary> /// <param name="column">The column.</param> ICellStyle GetColumnStyle(int column); /// <summary> /// Adds a merged region of cells (hence those cells form one) /// </summary> /// <param name="region">(rowfrom/colfrom-rowto/colto) to merge.</param> /// <returns>index of this region</returns> int AddMergedRegion(NPOI.SS.Util.CellRangeAddress region); /// <summary> /// Adds a merged region of cells (hence those cells form one). /// Skips validation. It is possible to create overlapping merged regions /// or create a merged region that intersects a multi-cell array formula /// with this formula, which may result in a corrupt workbook. /// /// To check for merged regions overlapping array formulas or other merged regions /// after addMergedRegionUnsafe has been called, call {@link #validateMergedRegions()}, which runs in O(n^2) time. /// </summary> /// <param name="region">region to merge</param> /// <returns>index of this region</returns> /// <exception cref="ArgumentException">if region contains fewer than 2 cells</exception> int AddMergedRegionUnsafe(CellRangeAddress region); /// <summary> /// Verify that merged regions do not intersect multi-cell array formulas and /// no merged regions intersect another merged region in this sheet. /// </summary> /// <exception cref="NPOI.Util.InvalidOperationException">if region intersects with a multi-cell array formula</exception> /// <exception cref="NPOI.Util.InvalidOperationException">if at least one region intersects with another merged region in this sheet</exception> void ValidateMergedRegions(); /// <summary> /// Determine whether printed output for this sheet will be horizontally centered. /// </summary> bool HorizontallyCenter { get; set; } /// <summary> /// Determine whether printed output for this sheet will be vertically centered. /// </summary> bool VerticallyCenter { get; set; } /// <summary> /// Removes a merged region of cells (hence letting them free) /// </summary> /// <param name="index">index of the region to unmerge</param> void RemoveMergedRegion(int index); /// <summary> /// Removes a number of merged regions of cells (hence letting them free) /// </summary> /// <param name="indices">A set of the regions to unmerge</param> void RemoveMergedRegions(IList<int> indices); /// <summary> /// Returns the number of merged regions /// </summary> int NumMergedRegions { get; } /// <summary> /// Returns the merged region at the specified index /// </summary> /// <param name="index">The index.</param> CellRangeAddress GetMergedRegion(int index); /// <summary> /// Returns the list of merged regions. /// </summary> List<CellRangeAddress> MergedRegions { get; } /// <summary> /// Gets the row enumerator. /// </summary> /// <returns> /// an iterator of the PHYSICAL rows. Meaning the 3rd element may not /// be the third row if say for instance the second row is undefined. /// Call <see cref="NPOI.SS.UserModel.IRow.RowNum"/> on each row /// if you care which one it is. /// </returns> IEnumerator GetRowEnumerator(); /// <summary> /// Get the row enumerator /// </summary> /// <returns></returns> IEnumerator GetEnumerator(); /// <summary> /// Gets the flag indicating whether the window should show 0 (zero) in cells Containing zero value. /// When false, cells with zero value appear blank instead of showing the number zero. /// </summary> /// <value>whether all zero values on the worksheet are displayed.</value> bool DisplayZeros { get; set; } /// <summary> /// Gets or sets a value indicating whether the sheet displays Automatic Page Breaks. /// </summary> bool Autobreaks { get; set; } /// <summary> /// Get whether to display the guts or not, /// </summary> /// <value>default value is true</value> bool DisplayGuts { get; set; } /// <summary> /// Flag indicating whether the Fit to Page print option is enabled. /// </summary> bool FitToPage { get; set; } /// <summary> /// Flag indicating whether summary rows appear below detail in an outline, when applying an outline. /// /// /// When true a summary row is inserted below the detailed data being summarized and a /// new outline level is established on that row. /// /// /// When false a summary row is inserted above the detailed data being summarized and a new outline level /// is established on that row. /// /// </summary> /// <returns><c>true</c> if row summaries appear below detail in the outline</returns> bool RowSumsBelow { get; set; } /// <summary> /// Flag indicating whether summary columns appear to the right of detail in an outline, when applying an outline. /// /// /// When true a summary column is inserted to the right of the detailed data being summarized /// and a new outline level is established on that column. /// /// /// When false a summary column is inserted to the left of the detailed data being /// summarized and a new outline level is established on that column. /// /// </summary> /// <returns><c>true</c> if col summaries appear right of the detail in the outline</returns> bool RowSumsRight { get; set; } /// <summary> /// Gets the flag indicating whether this sheet displays the lines /// between rows and columns to make editing and reading easier. /// </summary> /// <returns><c>true</c> if this sheet displays gridlines.</returns> bool IsPrintGridlines { get; set; } /// <summary> /// Get or set the flag indicating whether this sheet prints the /// row and column headings when printing. /// /// return true if this sheet prints row and column headings. /// </summary> bool IsPrintRowAndColumnHeadings { get; set; } /// <summary> /// Gets the print Setup object. /// </summary> /// <returns>The user model for the print Setup object.</returns> IPrintSetup PrintSetup { get; } /// <summary> /// Gets the user model for the default document header. /// <p/> /// Note that XSSF offers more kinds of document headers than HSSF does /// /// </summary> /// <returns>the document header. Never <code>null</code></returns> IHeader Header { get; } /// <summary> /// Gets the user model for the default document footer. /// <p/> /// Note that XSSF offers more kinds of document footers than HSSF does. /// </summary> /// <returns>the document footer. Never <code>null</code></returns> IFooter Footer { get; } /// <summary> /// Gets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <returns>the size of the margin</returns> double GetMargin(MarginType margin); /// <summary> /// Sets the size of the margin in inches. /// </summary> /// <param name="margin">which margin to get</param> /// <param name="size">the size of the margin</param> void SetMargin(MarginType margin, double size); /// <summary> /// Answer whether protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool Protect { get; } /// <summary> /// Sets the protection enabled as well as the password /// </summary> /// <param name="password">to set for protection. Pass <code>null</code> to remove protection</param> void ProtectSheet(String password); /// <summary> /// Answer whether scenario protection is enabled or disabled /// </summary> /// <returns>true => protection enabled; false => protection disabled</returns> bool ScenarioProtect { get; } /// <summary> /// Gets or sets the tab color of the _sheet /// </summary> short TabColorIndex { get; set; } /// <summary> /// Returns the top-level drawing patriach, if there is one. /// This will hold any graphics or charts for the _sheet. /// WARNING - calling this will trigger a parsing of the /// associated escher records. Any that aren't supported /// (such as charts and complex drawing types) will almost /// certainly be lost or corrupted when written out. Only /// use this with simple drawings, otherwise call /// HSSFSheet#CreateDrawingPatriarch() and /// start from scratch! /// </summary> /// <value>The drawing patriarch.</value> IDrawing DrawingPatriarch { get; } /// <summary> /// Sets the zoom magnication for the sheet. The zoom is expressed as a /// fraction. For example to express a zoom of 75% use 3 for the numerator /// and 4 for the denominator. /// </summary> /// <param name="numerator">The numerator for the zoom magnification.</param> /// <param name="denominator">denominator for the zoom magnification.</param> [Obsolete("deprecated 2015-11-23 (circa POI 3.14beta1). Use {@link #setZoom(int)} instead.")] void SetZoom(int numerator, int denominator); /** * Window zoom magnification for current view representing percent values. * Valid values range from 10 to 400. Horizontal & Vertical scale together. * * For example: * <pre> * 10 - 10% * 20 - 20% * ... * 100 - 100% * ... * 400 - 400% * </pre> * * @param scale window zoom magnification * @throws IllegalArgumentException if scale is invalid */ void SetZoom(int scale); /// <summary> /// The top row in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row.</value> short TopRow { get; set; } /// <summary> /// The left col in the visible view when the sheet is /// first viewed after opening it in a viewer /// </summary> /// <value>the rownum (0 based) of the top row</value> short LeftCol { get; set; } /// <summary> /// Sets desktop window pane display area, when the file is first opened in a viewer. /// </summary> /// <param name="toprow">the top row to show in desktop window pane</param> /// <param name="leftcol">the left column to show in desktop window pane</param> void ShowInPane(int toprow, int leftcol); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around. /// /// Calls shiftRows(startRow, endRow, n, false, false); /// /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> void ShiftRows(int startRow, int endRow, int n); /// <summary> /// Shifts rows between startRow and endRow n number of rows. /// If you use a negative number, it will shift rows up. /// Code ensures that rows don't wrap around /// /// Additionally shifts merged regions that are completely defined in these /// rows (ie. merged 2 cells on a row to be shifted). /// </summary> /// <param name="startRow">the row to start shifting</param> /// <param name="endRow">the row to end shifting</param> /// <param name="n">the number of rows to shift</param> /// <param name="copyRowHeight">whether to copy the row height during the shift</param> /// <param name="resetOriginalRowHeight">whether to set the original row's height to the default</param> void ShiftRows(int startRow, int endRow, int n, bool copyRowHeight, bool resetOriginalRowHeight); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split</param> /// <param name="rowSplit">Vertical position of split</param> /// <param name="leftmostColumn">Top row visible in bottom pane</param> /// <param name="topRow">Left column visible in right pane</param> void CreateFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow); /// <summary> /// Creates a split (freezepane). Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="colSplit">Horizonatal position of split.</param> /// <param name="rowSplit">Vertical position of split.</param> void CreateFreezePane(int colSplit, int rowSplit); /// <summary> /// Creates a split pane. Any existing freezepane or split pane is overwritten. /// </summary> /// <param name="xSplitPos">Horizonatal position of split (in 1/20th of a point)</param> /// <param name="ySplitPos">Vertical position of split (in 1/20th of a point)</param> /// <param name="leftmostColumn">Left column visible in right pane</param> /// <param name="topRow">Top row visible in bottom pane</param> /// <param name="activePane">Active pane. One of: PANE_LOWER_RIGHT, PANE_UPPER_RIGHT, PANE_LOWER_LEFT, PANE_UPPER_LEFT</param> /// @see #PANE_LOWER_LEFT /// @see #PANE_LOWER_RIGHT /// @see #PANE_UPPER_LEFT /// @see #PANE_UPPER_RIGHT void CreateSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, PanePosition activePane); /// <summary> /// Returns the information regarding the currently configured pane (split or freeze) /// </summary> /// <value>if no pane configured returns <c>null</c> else return the pane information.</value> PaneInformation PaneInformation { get; } /// <summary> /// Returns if gridlines are displayed /// </summary> bool DisplayGridlines { get; set; } /// <summary> /// Returns if formulas are displayed /// </summary> bool DisplayFormulas { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool DisplayRowColHeadings { get; set; } /// <summary> /// Returns if RowColHeadings are displayed. /// </summary> bool IsActive { get; set; } /// <summary> /// Determines if there is a page break at the indicated row /// </summary> /// <param name="row">The row.</param> bool IsRowBroken(int row); /// <summary> /// Removes the page break at the indicated row /// </summary> /// <param name="row">The row index.</param> void RemoveRowBreak(int row); /// <summary> /// Retrieves all the horizontal page breaks /// </summary> /// <value>all the horizontal page breaks, or null if there are no row page breaks</value> int[] RowBreaks { get; } /// <summary> /// Retrieves all the vertical page breaks /// </summary> /// <value>all the vertical page breaks, or null if there are no column page breaks.</value> int[] ColumnBreaks { get; } /// <summary> /// Sets the active cell. /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> //void SetActiveCell(int row, int column); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="firstRow">The firstrow.</param> /// <param name="lastRow">The lastrow.</param> /// <param name="firstColumn">The firstcolumn.</param> /// <param name="lastColumn">The lastcolumn.</param> void SetActiveCellRange(int firstRow, int lastRow, int firstColumn, int lastColumn); /// <summary> /// Sets the active cell range. /// </summary> /// <param name="cellranges">The cellranges.</param> /// <param name="activeRange">The index of the active range.</param> /// <param name="activeRow">The active row in the active range</param> /// <param name="activeColumn">The active column in the active range</param> void SetActiveCellRange(List<CellRangeAddress8Bit> cellranges, int activeRange, int activeRow, int activeColumn); /// <summary> /// Sets a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void SetColumnBreak(int column); /// <summary> /// Sets the row break. /// </summary> /// <param name="row">The row.</param> void SetRowBreak(int row); /// <summary> /// Determines if there is a page break at the indicated column /// </summary> /// <param name="column">The column index.</param> bool IsColumnBroken(int column); /// <summary> /// Removes a page break at the indicated column /// </summary> /// <param name="column">The column.</param> void RemoveColumnBreak(int column); /// <summary> /// Expands or collapses a column group. /// </summary> /// <param name="columnNumber">One of the columns in the group.</param> /// <param name="collapsed">if set to <c>true</c>collapse group.<c>false</c>expand group.</param> void SetColumnGroupCollapsed(int columnNumber, bool collapsed); /// <summary> /// Create an outline for the provided column range. /// </summary> /// <param name="fromColumn">beginning of the column range.</param> /// <param name="toColumn">end of the column range.</param> void GroupColumn(int fromColumn, int toColumn); /// <summary> /// Ungroup a range of columns that were previously groupped /// </summary> /// <param name="fromColumn">start column (0-based).</param> /// <param name="toColumn">end column (0-based).</param> void UngroupColumn(int fromColumn, int toColumn); /// <summary> /// Tie a range of rows toGether so that they can be collapsed or expanded /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void GroupRow(int fromRow, int toRow); /// <summary> /// Ungroup a range of rows that were previously groupped /// </summary> /// <param name="fromRow">start row (0-based)</param> /// <param name="toRow">end row (0-based)</param> void UngroupRow(int fromRow, int toRow); /// <summary> /// Set view state of a groupped range of rows /// </summary> /// <param name="row">start row of a groupped range of rows (0-based).</param> /// <param name="collapse">whether to expand/collapse the detail rows.</param> void SetRowGroupCollapsed(int row, bool collapse); /// <summary> /// Sets the default column style for a given column. POI will only apply this style to new cells Added to the sheet. /// </summary> /// <param name="column">the column index</param> /// <param name="style">the style to set</param> void SetDefaultColumnStyle(int column, ICellStyle style); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column); /// <summary> /// Adjusts the column width to fit the contents. /// </summary> /// <param name="column">the column index.</param> /// <param name="useMergedCells">whether to use the contents of merged cells when /// calculating the width of the column. Default is to ignore merged cells.</param> /// <remarks> /// This process can be relatively slow on large sheets, so this should /// normally only be called once per column, at the end of your /// processing. /// </remarks> void AutoSizeColumn(int column, bool useMergedCells); /// <summary> /// Returns cell comment for the specified row and column /// </summary> /// <param name="row">The row.</param> /// <param name="column">The column.</param> [Obsolete("deprecated as of 2015-11-23 (circa POI 3.14beta1). Use {@link #getCellComment(CellAddress)} instead.")] IComment GetCellComment(int row, int column); /// <summary> /// Returns cell comment for the specified location /// </summary> /// <param name="ref1">cell location</param> /// <returns>return cell comment or null if not found</returns> IComment GetCellComment(CellAddress ref1); /// <summary> /// Returns all cell comments on this sheet. /// </summary> /// <returns>return A Dictionary of each Comment in the sheet, keyed on the cell address where the comment is located.</returns> Dictionary<CellAddress, IComment> GetCellComments(); /// <summary> /// Creates the top-level drawing patriarch. /// </summary> IDrawing CreateDrawingPatriarch(); /// <summary> /// Gets the parent workbook. /// </summary> IWorkbook Workbook { get; } /// <summary> /// Gets the name of the sheet. /// </summary> String SheetName { get; } /// <summary> /// Gets or sets a value indicating whether this sheet is currently selected. /// </summary> bool IsSelected { get; set; } /// <summary> /// Sets whether sheet is selected. /// </summary> /// <param name="value">Whether to select the sheet or deselect the sheet.</param> void SetActive(bool value); /// <summary> /// Sets array formula to specified region for result. /// </summary> /// <param name="formula">text representation of the formula</param> /// <param name="range">Region of array formula for result</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> SetArrayFormula(String formula, CellRangeAddress range); /// <summary> /// Remove a Array Formula from this sheet. All cells contained in the Array Formula range are removed as well /// </summary> /// <param name="cell">any cell within Array Formula range</param> /// <returns>the <see cref="ICellRange{ICell}"/> of cells affected by this change</returns> ICellRange<ICell> RemoveArrayFormula(ICell cell); /// <summary> /// Checks if the provided region is part of the merged regions. /// </summary> /// <param name="mergedRegion">Region searched in the merged regions</param> /// <returns><c>true</c>, when the region is contained in at least one of the merged regions</returns> bool IsMergedRegion(CellRangeAddress mergedRegion); /// <summary> /// Create an instance of a DataValidationHelper. /// </summary> /// <returns>Instance of a DataValidationHelper</returns> IDataValidationHelper GetDataValidationHelper(); /// <summary> /// Returns the list of DataValidation in the sheet. /// </summary> /// <returns>list of DataValidation in the sheet</returns> List<IDataValidation> GetDataValidations(); /// <summary> /// Creates a data validation object /// </summary> /// <param name="dataValidation">The data validation object settings</param> void AddValidationData(IDataValidation dataValidation); /// <summary> /// Enable filtering for a range of cells /// </summary> /// <param name="range">the range of cells to filter</param> IAutoFilter SetAutoFilter(CellRangeAddress range); /// <summary> /// The 'Conditional Formatting' facet for this <c>Sheet</c> /// </summary> /// <returns>conditional formatting rule for this sheet</returns> ISheetConditionalFormatting SheetConditionalFormatting { get; } /// <summary> /// Whether the text is displayed in right-to-left mode in the window /// </summary> bool IsRightToLeft { get; set; } /// <summary> /// Get or set the repeating rows used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating rows cover a range of contiguous rows, e.g.: /// <pre> /// Sheet1!$1:$1 /// Sheet2!$5:$8 /// </pre> /// The {@link CellRangeAddress} returned contains a column part which spans /// all columns, and a row part which specifies the contiguous range of /// repeating rows. /// <p/> /// If the Sheet does not have any repeating rows defined, null is returned. /// </summary> CellRangeAddress RepeatingRows { get; set; } /// <summary> /// Gets or set the repeating columns used when printing the sheet, as found in File->PageSetup->Sheet. /// <p/> /// Repeating columns cover a range of contiguous columns, e.g.: /// <pre> /// Sheet1!$A:$A /// Sheet2!$C:$F /// </pre> /// The {@link CellRangeAddress} returned contains a row part which spans all /// rows, and a column part which specifies the contiguous range of /// repeating columns. /// <p/> /// If the Sheet does not have any repeating columns defined, null is /// returned. /// </summary> CellRangeAddress RepeatingColumns { get; set; } /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name); /// <summary> /// Copy sheet with a new name /// </summary> /// <param name="Name">new sheet name</param> /// <param name="copyStyle">whether to copy styles</param> /// <returns>cloned sheet</returns> ISheet CopySheet(String Name, Boolean copyStyle); /// <summary> /// Returns the column outline level. Increased as you /// put it into more groups (outlines), reduced as /// you take it out of them. /// </summary> /// <param name="columnIndex"></param> /// <returns></returns> int GetColumnOutlineLevel(int columnIndex); bool IsDate1904(); /// <summary> /// Get a Hyperlink in this sheet anchored at row, column /// </summary> /// <param name="row"></param> /// <param name="column"></param> /// <returns>return hyperlink if there is a hyperlink anchored at row, column; otherwise returns null</returns> IHyperlink GetHyperlink(int row, int column); /// <summary> /// Get a Hyperlink in this sheet located in a cell specified by {code addr} /// </summary> /// <param name="addr">The address of the cell containing the hyperlink</param> /// <returns>return hyperlink if there is a hyperlink anchored at {@code addr}; otherwise returns {@code null}</returns> IHyperlink GetHyperlink(CellAddress addr); /// <summary> /// Get a list of Hyperlinks in this sheet /// </summary> /// <returns>return Hyperlinks for the sheet</returns> List<IHyperlink> GetHyperlinkList(); /// <summary> /// get or set location of the active cell, e.g. <code>A1</code>. /// </summary> CellAddress ActiveCell { get; set; } void CopyTo(IWorkbook dest, string name, bool copyStyle, bool keepFormulas); } }
using UnityEngine; using System.Collections.Generic; using System.Linq; namespace Polybrush { public class z_SplatWeight { private Dictionary<z_MeshChannel, int> map; float[] values; public Vector4 this[z_MeshChannel channel] { get { return GetVec4(map[channel]); } set { SetVec4(map[channel], value); } } public float this[z_AttributeLayout attribute] { get { return GetAttributeValue(attribute); } set { SetAttributeValue(attribute, value); } } public float this[int valueIndex] { get { return values[valueIndex]; } set { values[valueIndex] = value; } } public z_SplatWeight(Dictionary<z_MeshChannel, int> map) { this.map = new Dictionary<z_MeshChannel, int>(); foreach(var v in map) this.map.Add(v.Key, v.Value); this.values = new float[map.Count * 4]; } /** * Deep copy constructor. */ public z_SplatWeight(z_SplatWeight rhs) { this.map = new Dictionary<z_MeshChannel, int>(); foreach(var kvp in rhs.map) this.map.Add(kvp.Key, kvp.Value); int len = rhs.values.Length; this.values = new float[len]; System.Array.Copy(rhs.values, this.values, len); } public static Dictionary<z_MeshChannel, int> GetChannelMap(z_AttributeLayout[] attributes) { int index = 0; Dictionary<z_MeshChannel, int> channelMap = new Dictionary<z_MeshChannel, int>(); foreach(z_MeshChannel ch in attributes.Select(x => x.channel).Distinct()) channelMap.Add(ch, index++); return channelMap; } public List<int> GetAffectedIndicesWithMask(z_AttributeLayout[] attributes, int mask) { List<int> affected = new List<int>(); foreach(z_AttributeLayout attrib in attributes) { if(attrib.mask == mask) affected.Add( map[attrib.channel] * 4 + (int) attrib.index ); } return affected; } public bool MatchesAttributes(z_AttributeLayout[] attributes) { for(int i = 0; i < attributes.Length; i++) if(!map.ContainsKey(attributes[i].channel)) return false; return true; } private Vector4 GetVec4(int index) { return new Vector4( values[index * 4 ], values[index * 4 + 1], values[index * 4 + 2], values[index * 4 + 3]); } private void SetVec4(int index, Vector4 value) { values[index * 4 ] = value.x; values[index * 4 + 1] = value.y; values[index * 4 + 2] = value.z; values[index * 4 + 3] = value.w; } public float GetAttributeValue(z_AttributeLayout attrib) { return values[map[attrib.channel] * 4 + (int) attrib.index]; } public void SetAttributeValue(z_AttributeLayout attrib, float value) { values[map[attrib.channel] * 4 + (int) attrib.index] = value; } /** * Copy values array to another splatweight. This function doesn't check * that attribute layouts are matching; musht do this yourself. */ public void CopyTo(z_SplatWeight other) { for(int i = 0; i < values.Length; i++) other.values[i] = this.values[i]; } public void Lerp(z_SplatWeight lhs, z_SplatWeight rhs, float alpha) { int len = values.Length; if(len == 4) { values[0] = Mathf.LerpUnclamped(lhs.values[0], rhs.values[0], alpha); values[1] = Mathf.LerpUnclamped(lhs.values[1], rhs.values[1], alpha); values[2] = Mathf.LerpUnclamped(lhs.values[2], rhs.values[2], alpha); values[3] = Mathf.LerpUnclamped(lhs.values[3], rhs.values[3], alpha); } else if(len == 8) { values[0] = Mathf.LerpUnclamped(lhs.values[0], rhs.values[0], alpha); values[1] = Mathf.LerpUnclamped(lhs.values[1], rhs.values[1], alpha); values[2] = Mathf.LerpUnclamped(lhs.values[2], rhs.values[2], alpha); values[3] = Mathf.LerpUnclamped(lhs.values[3], rhs.values[3], alpha); values[4] = Mathf.LerpUnclamped(lhs.values[4], rhs.values[4], alpha); values[5] = Mathf.LerpUnclamped(lhs.values[5], rhs.values[5], alpha); values[6] = Mathf.LerpUnclamped(lhs.values[6], rhs.values[6], alpha); values[7] = Mathf.LerpUnclamped(lhs.values[7], rhs.values[7], alpha); } else if(len == 16) { values[0] = Mathf.LerpUnclamped(lhs.values[0], rhs.values[0], alpha); values[1] = Mathf.LerpUnclamped(lhs.values[1], rhs.values[1], alpha); values[2] = Mathf.LerpUnclamped(lhs.values[2], rhs.values[2], alpha); values[3] = Mathf.LerpUnclamped(lhs.values[3], rhs.values[3], alpha); values[4] = Mathf.LerpUnclamped(lhs.values[4], rhs.values[4], alpha); values[5] = Mathf.LerpUnclamped(lhs.values[5], rhs.values[5], alpha); values[6] = Mathf.LerpUnclamped(lhs.values[6], rhs.values[6], alpha); values[7] = Mathf.LerpUnclamped(lhs.values[7], rhs.values[7], alpha); values[8] = Mathf.LerpUnclamped(lhs.values[8], rhs.values[8], alpha); values[9] = Mathf.LerpUnclamped(lhs.values[9], rhs.values[9], alpha); values[10] = Mathf.LerpUnclamped(lhs.values[10], rhs.values[10], alpha); values[11] = Mathf.LerpUnclamped(lhs.values[11], rhs.values[11], alpha); values[12] = Mathf.LerpUnclamped(lhs.values[12], rhs.values[12], alpha); values[13] = Mathf.LerpUnclamped(lhs.values[13], rhs.values[13], alpha); values[14] = Mathf.LerpUnclamped(lhs.values[14], rhs.values[14], alpha); values[15] = Mathf.LerpUnclamped(lhs.values[15], rhs.values[15], alpha); } else { for(int i = 0; i < lhs.values.Length; i++) values[i] = Mathf.LerpUnclamped(lhs.values[i], rhs.values[i], alpha); } } public void Lerp(z_SplatWeight lhs, z_SplatWeight rhs, float alpha, List<int> mask) { // optimize for some common values // unrolling the loop in these smaller cases can improve performances by ~33% if(mask.Count == 4) { values[mask[0]] = Mathf.LerpUnclamped(lhs.values[mask[0]], rhs.values[mask[0]], alpha); values[mask[1]] = Mathf.LerpUnclamped(lhs.values[mask[1]], rhs.values[mask[1]], alpha); values[mask[2]] = Mathf.LerpUnclamped(lhs.values[mask[2]], rhs.values[mask[2]], alpha); values[mask[3]] = Mathf.LerpUnclamped(lhs.values[mask[3]], rhs.values[mask[3]], alpha); } else if(mask.Count == 8) { values[mask[0]] = Mathf.LerpUnclamped(lhs.values[mask[0]], rhs.values[mask[0]], alpha); values[mask[1]] = Mathf.LerpUnclamped(lhs.values[mask[1]], rhs.values[mask[1]], alpha); values[mask[2]] = Mathf.LerpUnclamped(lhs.values[mask[2]], rhs.values[mask[2]], alpha); values[mask[3]] = Mathf.LerpUnclamped(lhs.values[mask[3]], rhs.values[mask[3]], alpha); values[mask[4]] = Mathf.LerpUnclamped(lhs.values[mask[4]], rhs.values[mask[4]], alpha); values[mask[5]] = Mathf.LerpUnclamped(lhs.values[mask[5]], rhs.values[mask[5]], alpha); values[mask[6]] = Mathf.LerpUnclamped(lhs.values[mask[6]], rhs.values[mask[6]], alpha); values[mask[7]] = Mathf.LerpUnclamped(lhs.values[mask[7]], rhs.values[mask[7]], alpha); } else { for(int i = 0; i < mask.Count; i++) values[mask[i]] = Mathf.LerpUnclamped(lhs.values[mask[i]], rhs.values[mask[i]], alpha); } } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach(var v in map) { sb.Append(v.Key.ToString()); sb.Append(": "); sb.AppendLine(GetVec4(v.Value).ToString("F2")); } return sb.ToString(); } } }
//! \file ImageMI4.cs //! \date Sun Jul 12 15:40:39 2015 //! \brief ShiinaRio engine image format. // // Copyright (C) 2015 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.ComponentModel.Composition; using System.IO; using System.Windows.Media; namespace GameRes.Formats.ShiinaRio { [Export(typeof(ImageFormat))] public class Mi4Format : ImageFormat { public override string Tag { get { return "MI4"; } } public override string Description { get { return "ShiinaRio image format"; } } public override uint Signature { get { return 0x3449414D; } } // 'MAI4' public override ImageMetaData ReadMetaData (Stream stream) { stream.Seek (8, SeekOrigin.Current); using (var input = new ArcView.Reader (stream)) { uint width = input.ReadUInt32(); uint height = input.ReadUInt32(); return new ImageMetaData { Width = width, Height = height, BPP = 24, }; } } public override ImageData Read (Stream stream, ImageMetaData info) { stream.Position = 0x10; using (var reader = new Reader (stream, (int)info.Width, (int)info.Height)) { reader.Unpack (); return ImageData.Create (info, PixelFormats.Bgr24, null, reader.Data); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("Mi4Format.Write not implemented"); } internal sealed class Reader : IDisposable { BinaryReader m_input; byte[] m_output; int m_stride; public byte[] Data { get { return m_output; } } public Reader (Stream file, int width, int height) { m_input = new ArcView.Reader (file); m_stride = width * 3; m_output = new byte[m_stride*height]; } uint m_bit_count; uint m_bits; void ResetBits () { m_bits = m_input.ReadUInt32(); m_bit_count = 32; } uint GetBit () { uint bit = m_bits >> 31; m_bits <<= 1; if (0 == --m_bit_count) { m_bits = m_input.ReadUInt32(); m_bit_count = 32; } return bit; } uint GetBits (int count) { uint bits = 0; while (count --> 0) { bits = (bits << 1) | GetBit(); } return bits; } public void Unpack () { ResetBits(); int dst = 0; byte b = 0, g = 0, r = 0; while (dst < m_output.Length) { if (GetBit() == 0) { if (GetBit() != 0) { b = m_input.ReadByte(); g = m_input.ReadByte(); r = m_input.ReadByte(); } else if (GetBit() != 0) { byte v = (byte)(GetBits(2)); if (3 == v) { b = m_output[dst - m_stride]; g = m_output[dst - m_stride + 1]; r = m_output[dst - m_stride + 2]; } else { b += (byte)(v - 1); v = (byte)GetBits (2); if (3 == v) { if (GetBit() != 0) { b = m_output[dst - m_stride - 3]; g = m_output[dst - m_stride - 2]; r = m_output[dst - m_stride - 1]; } else { b = m_output[dst - m_stride + 3]; g = m_output[dst - m_stride + 4]; r = m_output[dst - m_stride + 5]; } } else { g += (byte)(v - 1); r += (byte)(GetBits(2) - 1); } } } else if (GetBit() != 0) { byte v = (byte)(GetBits(3)); if (7 == v) { b = m_output[dst - m_stride]; g = m_output[dst - m_stride + 1]; r = m_output[dst - m_stride + 2]; b += (byte)(GetBits(3) - 3); g += (byte)(GetBits(3) - 3); r += (byte)(GetBits(3) - 3); } else { b += (byte)(v - 3); g += (byte)(GetBits(3) - 3); r += (byte)(GetBits(3) - 3); } } else if (GetBit() != 0) { b += (byte)(GetBits(4) - 7); g += (byte)(GetBits(4) - 7); r += (byte)(GetBits(4) - 7); } else { b += (byte)(GetBits(5) - 15); g += (byte)(GetBits(5) - 15); r += (byte)(GetBits(5) - 15); } } m_output[dst++] = b; m_output[dst++] = g; m_output[dst++] = r; } } #region IDisposable Members bool disposed = false; public void Dispose () { if (!disposed) { m_input.Dispose (); disposed = true; } GC.SuppressFinalize (this); } #endregion } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; using Hydra.Framework; using Hydra.Framework.Helpers; using Hydra.Framework.Java; using Hydra.Framework.Mapping.CoordinateSystems; using Hydra.Framework.Conversions; namespace Hydra.DomainModel { // //********************************************************************** /// <summary> /// Emergency Details (Panic / Tampering) /// </summary> //********************************************************************** // [Serializable] [DataContract(Namespace = CommonConstants.DATA_NAMESPACE)] public class InternalEmergency : AbstractInternalData { #region Member Variables // //********************************************************************** /// <summary> /// Reason for the Emergency /// </summary> //********************************************************************** // [DataMember(Name = "Reason")] public int Reason { get; set; } // //********************************************************************** /// <summary> /// Tamper State Type /// </summary> //********************************************************************** // [DataMember(Name = "TamperState")] public int TamperState { get; set; } // //********************************************************************** /// <summary> /// Number of Times Tampered With /// </summary> //********************************************************************** // [DataMember(Name = "TamperOpenCount")] public int TamperOpenCount { get; set; } // // ********************************************************************** /// <summary> /// Last Received Time that this emergency instance was called /// </summary> // ********************************************************************** // [DataMember(Name = "LastReceivedTime")] public DateTime LastReceivedTime { get; set; } // // ********************************************************************** /// <summary> /// Last Received Sequence NUmber /// </summary> // ********************************************************************** // [DataMember(Name = "LastReceivedSequence")] public int LastReceivedSequence { get; set; } // // ********************************************************************** /// <summary> /// Call Button Pressed /// </summary> // ********************************************************************** // [DataMember(Name = "CallButtonPressed")] public bool CallButtonPressed { get; set; } // // ********************************************************************** /// <summary> /// Red Button Pressed /// </summary> // ********************************************************************** // [DataMember(Name = "RedButtonPressed")] public bool RedButtonPressed { get; set; } // // ********************************************************************** /// <summary> /// Green Button Pressed /// </summary> // ********************************************************************** // [DataMember(Name = "GreenButtonPressed")] public bool GreenButtonPressed { get; set; } #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalEmergency"/> class. /// </summary> // ********************************************************************** // public InternalEmergency() : base(InternalLocationServiceType.Internal) { Log.Entry(); Log.Exit(); } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:InternalEmergency"/> class. /// </summary> /// <param name="changedOn">The changed on.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="reason">The reason.</param> /// <param name="tamperState">State of the tamper.</param> /// <param name="tamperOpenCount">The tamper open count.</param> /// <param name="lastReceivedTime">The last received time.</param> /// <param name="lastReceivedSequence">The last received sequence.</param> /// <param name="callButtonPressed">if set to <c>true</c> [call button pressed].</param> /// <param name="redButtonPressed">if set to <c>true</c> [red button pressed].</param> /// <param name="greenButtonPressed">if set to <c>true</c> [green button pressed].</param> //********************************************************************** // public InternalEmergency(DateTime changedOn, int objectId, int parentId, int reason, int tamperState, int tamperOpenCount, DateTime lastReceivedTime, int lastReceivedSequence, bool callButtonPressed, bool redButtonPressed, bool greenButtonPressed) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn) { Log.Entry(changedOn, reason, tamperState, tamperOpenCount); Reason = reason; TamperState = tamperState; TamperOpenCount = tamperOpenCount; LastReceivedTime = lastReceivedTime; LastReceivedSequence = lastReceivedSequence; CallButtonPressed = callButtonPressed; RedButtonPressed = redButtonPressed; GreenButtonPressed = greenButtonPressed; Log.Exit(); } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalEmergency"/> class. /// </summary> /// <param name="changedOn">The changed on.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="reason">The reason.</param> /// <param name="tamperState">State of the tamper.</param> /// <param name="tamperOpenCount">The tamper open count.</param> /// <param name="lastReceivedTime">The last received time.</param> /// <param name="callButtonPressed">if set to <c>true</c> [call button pressed].</param> /// <param name="redButtonPressed">if set to <c>true</c> [red button pressed].</param> /// <param name="greenButtonPressed">if set to <c>true</c> [green button pressed].</param> // ********************************************************************** // public InternalEmergency(DateTime changedOn, int objectId, int parentId, int reason, int tamperState, int tamperOpenCount, DateTime lastReceivedTime, bool callButtonPressed, bool redButtonPressed, bool greenButtonPressed) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn) { Log.Entry(changedOn, reason, tamperState, tamperOpenCount); Reason = reason; TamperState = tamperState; TamperOpenCount = tamperOpenCount; LastReceivedTime = lastReceivedTime; LastReceivedSequence = -1; CallButtonPressed = callButtonPressed; RedButtonPressed = redButtonPressed; GreenButtonPressed = greenButtonPressed; Log.Exit(); } #endregion #region Properties #endregion #region Private Methods #endregion } }
/* VRWebView * MiddleVR * (c) MiddleVR */ // UNITY_PRO_LICENSE exists starting from Unity 4.5 // For Unity 4.2 and 4.3 we always assume it's a Pro edition #if !(UNITY_PRO_LICENSE || UNITY_4_2 || UNITY_4_3) #define VRWEBVIEW_UNITY_FREE #endif using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public class VRWebView : MonoBehaviour { // Public attributes public int m_Width = 1024; public int m_Height = 768; public string m_URL = "http://www.middlevr.com/"; public float m_Zoom = 1.0f; // View management private vrWebView m_WebView = null; private vrImage m_Image = null; private Texture2D m_Texture = null; // Virtual mouse management private List<Camera> m_Cameras = null; private Vector2 m_VirtualMousePosition; private bool m_MouseButtonState = false; private bool m_IgnorePhysicalMouseInput = false; // Interaction private bool m_WandRayWasVisible = true; private static byte ALPHA_LIMIT = 50; #if VRWEBVIEW_UNITY_FREE // Unity Free texture management private Color32[] m_Pixels; private GCHandle m_PixelsHandle; #endif public vrImage image { get { return m_Image; } } public vrWebView webView { get { return m_WebView; } } protected void SetVirtualMouseButtonPressed() { if (m_WebView != null) { m_WebView.SendMouseButtonPressed((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } protected void SetVirtualMouseButtonReleased() { if (m_WebView != null) { m_WebView.SendMouseButtonReleased((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } // pos: texture coordinate of raycast hit protected void SetVirtualMousePosition(Vector2 pos) { if (m_WebView != null) { m_VirtualMousePosition = new Vector2(pos.x * m_Texture.width, (float)m_WebView.GetHeight() - (pos.y * m_Texture.height)); m_WebView.SendMouseMove((int)m_VirtualMousePosition.x, (int)m_VirtualMousePosition.y); } } public void IgnorePhysicalMouseInput() { m_IgnorePhysicalMouseInput = true; } public bool IsPixelEmpty(Vector2 iTextureCoord) { byte alpha = image.GetAlphaAtPoint((int)(iTextureCoord.x * m_Width), (int)(iTextureCoord.y * m_Height)); return alpha < ALPHA_LIMIT; } protected void Start () { // Check if we are running MiddleVR if(MiddleVR.VRKernel == null) { Debug.Log("[X] VRManager is missing from the scene !"); enabled = false; return; } m_VirtualMousePosition = new Vector2(0, 0); if (Application.isEditor) { // Get the vrCameras corresponding Cameras m_Cameras = new List<Camera>(); uint camerasNb = MiddleVR.VRDisplayMgr.GetCamerasNb(); for (uint i = 0; i < camerasNb; ++i) { vrCamera vrcamera = MiddleVR.VRDisplayMgr.GetCameraByIndex(i); GameObject cameraObj = GameObject.Find(vrcamera.GetName()); Camera camera = cameraObj.GetComponent<Camera>(); if (camera != null) { m_Cameras.Add(camera); } } } m_Texture = new Texture2D(m_Width, m_Height, TextureFormat.ARGB32, false); m_Texture.wrapMode = TextureWrapMode.Clamp; // Create vrImage and Texture2D #if VRWEBVIEW_UNITY_FREE // Texture2D.SetPixels takes RGBA. m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_RGBA); m_Pixels = m_Texture.GetPixels32 (0); m_PixelsHandle = GCHandle.Alloc(m_Pixels, GCHandleType.Pinned); #else // OpenGL and Direct3D 9: Memory order for texture upload is BGRA (little-endian representation of ARGB32) // Direct3D 11: Unity seems to ignore TextureFormat.ARGB32 and always creates an RGBA texture. // We let vrImage do the pixel format conversion because this operation is done in another thread. if (SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_RGBA); } else { m_Image = new vrImage("", (uint)m_Width, (uint)m_Height, VRImagePixelFormat.VRImagePixelFormat_BGRA); } #endif // Fill texture Color32[] colors = new Color32[(m_Width * m_Height)]; for (int i = 0; i < (m_Width * m_Height); i++) { colors[i].r = 0; colors[i].g = 0; colors[i].b = 0; colors[i].a = 0; } m_Texture.SetPixels32(colors); m_Texture.Apply(false, false); // Attach texture if (gameObject != null && gameObject.GetComponent<GUITexture>() == null && gameObject.GetComponent<Renderer>() != null) { var renderer = gameObject.GetComponent<Renderer>(); // Assign the material/shader to the object attached renderer.material = Resources.Load("VRWebViewMaterial", typeof(Material)) as Material; renderer.material.mainTexture = this.m_Texture; } else if (gameObject != null && gameObject.GetComponent<GUITexture>() != null ) { gameObject.GetComponent<GUITexture>().texture = this.m_Texture; } else { MiddleVR.VRLog(2, "VRWebView must be attached to a GameObject with a renderer or a GUITexture !"); enabled = false; return; } // Handle Cluster if ( MiddleVR.VRClusterMgr.IsServer() && ! MiddleVR.VRKernel.GetEditorMode() ) { MiddleVR.VRClusterMgr.AddSynchronizedObject( m_Image ); } if( ! MiddleVR.VRClusterMgr.IsClient() ) { m_WebView = new vrWebView("", GetAbsoluteURL( m_URL ) , (uint)m_Width, (uint)m_Height, m_Image ); m_WebView.SetZoom( m_Zoom ); } } #if !VRWEBVIEW_UNITY_FREE [DllImport("MiddleVR_UnityRendering")] private static extern void MiddleVR_CopyBufferToUnityNativeTexture(IntPtr iBuffer, IntPtr iNativeTexturePtr, uint iWidth, uint iHeight); #endif protected void Update () { // Handle mouse input if (!MiddleVR.VRClusterMgr.IsClient()) { if (!m_IgnorePhysicalMouseInput) { Vector2 mouseHit = new Vector2(0, 0); bool hasMouseHit = false; if (gameObject.GetComponent<GUITexture>() != null) { // GUITexture mouse input Rect r = gameObject.GetComponent<GUITexture>().GetScreenRect(); if( Input.mousePosition.x >= r.x && Input.mousePosition.x < (r.x + r.width) && Input.mousePosition.y >= r.y && Input.mousePosition.y < (r.y + r.height) ) { float x = (Input.mousePosition.x - r.x) / r.width; float y = (Input.mousePosition.y - r.y) / r.height; mouseHit = new Vector2(x, y); hasMouseHit = true; } } else if( gameObject.GetComponent<Renderer>() != null && Application.isEditor ) { // 3D object mouse input mouseHit = GetClosestMouseHit(); if (mouseHit.x != -1 && mouseHit.y != -1) { hasMouseHit = true; } } if (hasMouseHit) { bool newMouseButtonState = Input.GetMouseButton(0); if (m_MouseButtonState == false && newMouseButtonState == true) { SetVirtualMousePosition(mouseHit); SetVirtualMouseButtonPressed(); } else if (m_MouseButtonState == true && newMouseButtonState == false) { SetVirtualMouseButtonReleased(); SetVirtualMousePosition(mouseHit); } else { SetVirtualMousePosition(mouseHit); } m_MouseButtonState = newMouseButtonState; } } m_IgnorePhysicalMouseInput = false; } // Handle texture update if ( m_Image.HasChanged() ) { using (vrImageFormat format = m_Image.GetImageFormat()) { if ((uint)m_Texture.width != format.GetWidth() || (uint)m_Texture.height != format.GetHeight()) { #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); #endif m_Texture.Resize((int)format.GetWidth(), (int)format.GetHeight()); m_Texture.Apply(false, false); #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); m_Pixels = m_Texture.GetPixels32 (0); m_PixelsHandle = GCHandle.Alloc(m_Pixels, GCHandleType.Pinned); #endif } if (format.GetWidth() > 0 && format.GetHeight() > 0) { #if VRWEBVIEW_UNITY_FREE m_Image.GetReadBufferData( m_PixelsHandle.AddrOfPinnedObject() ); m_Texture.SetPixels32(m_Pixels, 0); m_Texture.Apply(false, false); #else MiddleVR_CopyBufferToUnityNativeTexture(m_Image.GetReadBuffer(), m_Texture.GetNativeTexturePtr(), format.GetWidth(), format.GetHeight()); #endif } } } } protected void OnDestroy () { #if VRWEBVIEW_UNITY_FREE m_PixelsHandle.Free(); #endif } private Vector2 GetClosestMouseHit() { foreach( Camera camera in m_Cameras ) { RaycastHit[] hits = Physics.RaycastAll( camera.ScreenPointToRay(Input.mousePosition)); foreach (RaycastHit hit in hits) { if (hit.collider.gameObject == gameObject) { return hit.textureCoord; } } } return new Vector2(-1,-1); } private string GetAbsoluteURL( string iUrl ) { string url = iUrl; // If url does not start with http/https we assume it's a file if( !url.StartsWith( "http://" ) && !url.StartsWith( "https://" ) ) { if( url.StartsWith( "file://" ) ) { url = url.Substring(7, url.Length-7 ); if( Application.platform == RuntimePlatform.WindowsPlayer && url.StartsWith( "/" ) ) { url = url.Substring(1, url.Length-1); } } if( ! System.IO.Path.IsPathRooted( url ) ) { url = Application.dataPath + System.IO.Path.DirectorySeparatorChar + url; } if( Application.platform == RuntimePlatform.WindowsPlayer ) { url = "/" + url; } url = "file://" + url; } return url; } protected void OnMVRWandEnter(VRSelection iSelection) { // Force show ray and save state m_WandRayWasVisible = iSelection.SourceWand.IsRayVisible(); iSelection.SourceWand.ShowRay(true); } protected void OnMVRWandHover(VRSelection iSelection) { SetVirtualMousePosition(iSelection.TextureCoordinate); } protected void OnMVRWandButtonPressed(VRSelection iSelection) { SetVirtualMousePosition(iSelection.TextureCoordinate); SetVirtualMouseButtonPressed(); } protected void OnMVRWandButtonReleased(VRSelection iSelection) { SetVirtualMouseButtonReleased(); SetVirtualMousePosition(iSelection.TextureCoordinate); } protected void OnMVRWandExit(VRSelection iSelection) { // Unforce show ray iSelection.SourceWand.ShowRay(m_WandRayWasVisible); } protected void OnMVRTouchEnd(VRTouch iTouch) { SetVirtualMouseButtonPressed(); SetVirtualMouseButtonReleased(); } protected void OnMVRTouchMoved(VRTouch iTouch) { Vector3 fwd = -transform.TransformDirection(Vector3.up); Ray ray = new Ray(iTouch.TouchObject.transform.position, fwd); var collider = GetComponent<Collider>(); RaycastHit hit; if (collider != null && collider.Raycast(ray, out hit, 1.0F)) { if (hit.collider.gameObject == gameObject) { Vector2 mouseCursor = hit.textureCoord; SetVirtualMousePosition(mouseCursor); } } } protected void OnMVRTouchBegin(VRTouch iTouch) { Vector3 fwd = -transform.TransformDirection(Vector3.up); Ray ray = new Ray(iTouch.TouchObject.transform.position, fwd); var collider = GetComponent<Collider>(); RaycastHit hit; if (collider != null && collider.Raycast(ray, out hit, 1.0F)) { if (hit.collider.gameObject == gameObject) { Vector2 mouseCursor = hit.textureCoord; SetVirtualMousePosition(mouseCursor); } } } }
// // BrowseService.cs // // Authors: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // // Modifications by Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Net; using System.Text; using System.Collections; using System.Runtime.InteropServices; using Couchbase.Lite.Util; #if __IOS__ using AOT = ObjCRuntime; #endif namespace Mono.Zeroconf.Providers.Bonjour { public sealed class ServiceErrorEventArgs : EventArgs { public readonly ServiceError ErrorCode; public readonly string Stage; internal ServiceErrorEventArgs(string stage, ServiceError errorCode) { Stage = stage; ErrorCode = errorCode; } } public sealed class BrowseService : Service, IResolvableService, IDisposable { private static readonly string Tag = typeof(BrowseService).Name; private bool is_resolved = false; private bool resolve_pending = false; private Native.DNSServiceResolveReply resolve_reply_handler; private Native.DNSServiceQueryRecordReply query_record_reply_handler; private GCHandle _self; public event ServiceResolvedEventHandler Resolved { add { _resolved = (ServiceResolvedEventHandler)Delegate.Combine(_resolved, value); } remove { _resolved = (ServiceResolvedEventHandler)Delegate.Remove(_resolved, value); } } private event ServiceResolvedEventHandler _resolved; public event EventHandler<ServiceErrorEventArgs> Error; public BrowseService() { SetupCallbacks(); } public BrowseService(string name, string replyDomain, string regtype) : base(name, replyDomain, regtype) { SetupCallbacks(); } private void SetupCallbacks() { Log.To.Discovery.D(Tag, "Initializing {0}", this); resolve_reply_handler = new Native.DNSServiceResolveReply(OnResolveReply); query_record_reply_handler = new Native.DNSServiceQueryRecordReply(OnQueryRecordReply); } public void Resolve() { Resolve(false); } public void Resolve(bool requery) { if(resolve_pending) { return; } is_resolved = false; resolve_pending = true; if(requery) { InterfaceIndex = 0; } if (!_self.IsAllocated) { _self = GCHandle.Alloc(this); } ServiceRef sd_ref; Log.To.Discovery.V(Tag, "{0} preparing to enter DNSServiceResolve", this); ServiceError error = Native.DNSServiceResolve(out sd_ref, ServiceFlags.None, InterfaceIndex, Name, RegType, ReplyDomain, resolve_reply_handler, GCHandle.ToIntPtr(_self)); if(error != ServiceError.NoError) { Log.To.Discovery.W(Tag, "Error from DNSServiceResolve {0}", error); if (Error != null) { Error(this, new ServiceErrorEventArgs("Resolve", error)); sd_ref.Deallocate(); return; } } sd_ref.ProcessSingle(); } public void RefreshTxtRecord() { if (!_self.IsAllocated) { _self = GCHandle.Alloc(this); } // Should probably make this async? ServiceRef sd_ref; ServiceError error = Native.DNSServiceQueryRecord(out sd_ref, ServiceFlags.None, 0, fullname, ServiceType.TXT, ServiceClass.IN, query_record_reply_handler, GCHandle.ToIntPtr(_self)); if(error != ServiceError.NoError) { Error(this, new ServiceErrorEventArgs("RefreshTxtRecord", error)); sd_ref.Deallocate(); return; } sd_ref.ProcessSingle(ServiceParams.Timeout); } #if __IOS__ || __UNITY_APPLE__ [AOT.MonoPInvokeCallback(typeof(Native.DNSServiceResolveReply))] #endif private static void OnResolveReply(ServiceRef sdRef, ServiceFlags flags, uint interfaceIndex, ServiceError errorCode, string fullname, string hosttarget, ushort port, ushort txtLen, IntPtr txtRecord, IntPtr context) { var handle = GCHandle.FromIntPtr(context); var browseService = handle.Target as BrowseService; Log.To.Discovery.V(Tag, "Resolve reply received for {0} (0x{1}), entering DNSServiceQueryRecord next", browseService, sdRef.Raw.ToString("X")); browseService.is_resolved = true; browseService.resolve_pending = false; browseService.InterfaceIndex = interfaceIndex; browseService.FullName = fullname; browseService.Port = (ushort)IPAddress.NetworkToHostOrder((short)port); browseService.TxtRecord = new TxtRecord(txtLen, txtRecord); sdRef.Deallocate(); // Run an A query to resolve the IP address ServiceRef sd_ref; if (browseService.AddressProtocol == AddressProtocol.Any || browseService.AddressProtocol == AddressProtocol.IPv4) { ServiceError error = Native.DNSServiceQueryRecord(out sd_ref, ServiceFlags.None, interfaceIndex, hosttarget, ServiceType.A, ServiceClass.IN, browseService.query_record_reply_handler, context); if(error != ServiceError.NoError) { Log.To.Discovery.W(Tag, "Error in DNSServiceQueryRecord {0}", error); browseService.Error(browseService, new ServiceErrorEventArgs("ResolveReply (IPv4)", error)); sd_ref.Deallocate(); return; } sd_ref.ProcessSingle(ServiceParams.Timeout); } if (browseService.AddressProtocol == AddressProtocol.Any || browseService.AddressProtocol == AddressProtocol.IPv6) { ServiceError error = Native.DNSServiceQueryRecord(out sd_ref, ServiceFlags.None, interfaceIndex, hosttarget, ServiceType.AAAA, ServiceClass.IN, browseService.query_record_reply_handler, context); if(error != ServiceError.NoError) { if(error != ServiceError.NoError) { Log.To.Discovery.W(Tag, "Error in DNSServiceQueryRecord {0}", error); browseService.Error(browseService, new ServiceErrorEventArgs("ResolveReply (IPv6)", error)); sd_ref.Deallocate(); return; } } sd_ref.ProcessSingle(ServiceParams.Timeout); } } #if __IOS__ || __UNITY_APPLE__ [AOT.MonoPInvokeCallback(typeof(Native.DNSServiceQueryRecordReply))] #endif private static void OnQueryRecordReply(ServiceRef sdRef, ServiceFlags flags, uint interfaceIndex, ServiceError errorCode, string fullname, ServiceType rrtype, ServiceClass rrclass, ushort rdlen, IntPtr rdata, uint ttl, IntPtr context) { var handle = GCHandle.FromIntPtr(context); var browseService = handle.Target as BrowseService; switch(rrtype) { case ServiceType.A: IPAddress address; if(rdlen == 4) { // ~4.5 times faster than Marshal.Copy into byte[4] uint address_raw = (uint)(Marshal.ReadByte (rdata, 3) << 24); address_raw |= (uint)(Marshal.ReadByte (rdata, 2) << 16); address_raw |= (uint)(Marshal.ReadByte (rdata, 1) << 8); address_raw |= (uint)Marshal.ReadByte (rdata, 0); address = new IPAddress(address_raw); } else if(rdlen == 16) { byte [] address_raw = new byte[rdlen]; Marshal.Copy(rdata, address_raw, 0, rdlen); address = new IPAddress(address_raw, interfaceIndex); } else { break; } if(browseService.hostentry == null) { browseService.hostentry = new IPHostEntry(); browseService.hostentry.HostName = browseService.hosttarget; } if(browseService.hostentry.AddressList != null) { ArrayList list = new ArrayList(browseService.hostentry.AddressList); list.Add(address); browseService.hostentry.AddressList = list.ToArray(typeof(IPAddress)) as IPAddress []; } else { browseService.hostentry.AddressList = new IPAddress [] { address }; } Log.To.Discovery.V(Tag, "Query record reply received for {0} (0x{1})", browseService, sdRef.Raw.ToString("X")); ServiceResolvedEventHandler handler = browseService._resolved; if(handler != null) { handler(browseService, new ServiceResolvedEventArgs(browseService)); } break; case ServiceType.TXT: if(browseService.TxtRecord != null) { browseService.TxtRecord.Dispose(); } browseService.TxtRecord = new TxtRecord(rdlen, rdata); break; default: break; } sdRef.Deallocate(); } public bool IsResolved { get { return is_resolved; } } public override string ToString() { if (IsResolved) { return string.Format("BrowseService[IsResolved=True Name={0} IPAddresses={1} Port={2}]", Name, new LogJsonString(hostentry == null ? new string[0] : hostentry.AddressList.ToStringArray()), Port); } return "BrowseService[IsResolved=False]"; } public void Dispose() { if (_self.IsAllocated) { _self.Free(); } } } }
//! \file ArcCherry.cs //! \date Wed Jun 24 21:22:56 2015 //! \brief Cherry Soft archives implementation. // // Copyright (C) 2015 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 GameRes.Compression; namespace GameRes.Formats.Cherry { [Export(typeof(ArchiveFormat))] public class PakOpener : ArchiveFormat { public override string Tag { get { return "PAK/CHERRY"; } } public override string Description { get { return "Cherry Soft PACK resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public PakOpener () { Extensions = new string[] { "pak" }; } public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (0); if (!IsSaneCount (count)) return null; long base_offset = file.View.ReadUInt32 (4); if (base_offset >= file.MaxOffset || base_offset != (8 + count*0x18)) return null; var dir = ReadIndex (file, 8, count, base_offset, file); return dir != null ? new ArcFile (file, this, dir) : null; } protected List<Entry> ReadIndex (ArcView index, int index_offset, int count, long base_offset, ArcView file) { uint index_size = (uint)count * 0x18u; if (index_size > index.View.Reserve (index_offset, index_size)) return null; string arc_name = Path.GetFileNameWithoutExtension (file.Name); bool is_grp = arc_name.EndsWith ("GRP", StringComparison.InvariantCultureIgnoreCase); var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { string name = index.View.ReadString (index_offset, 0x10); if (0 == name.Length) return null; var offset = base_offset + index.View.ReadUInt32 (index_offset+0x10); Entry entry; if (is_grp) { entry = new Entry { Name = Path.ChangeExtension (name, "grp"), Type = "image", Offset = offset }; } else { entry = AutoEntry.Create (file, offset, name); } entry.Size = index.View.ReadUInt32 (index_offset+0x14); if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); index_offset += 0x18; } return dir; } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!arc.File.View.AsciiEqual (entry.Offset, "GsWIN SC File")) return arc.File.CreateStream (entry.Offset, entry.Size); var text_offset = 0x68 + arc.File.View.ReadUInt32 (entry.Offset+0x5C); var text_size = arc.File.View.ReadUInt32 (entry.Offset+0x60); if (0 == text_size || text_offset+text_size > entry.Size) return arc.File.CreateStream (entry.Offset, entry.Size); var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); for (uint i = 0; i < text_size; ++i) { data[text_offset+i] ^= (byte)i; } return new BinMemoryStream (data, entry.Name); } } internal class CherryPak : ArcFile { public CherryPak (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir) : base (arc, impl, dir) { } } [Export(typeof(ArchiveFormat))] public class Pak2Opener : PakOpener { public override string Tag { get { return "PAK/CHERRY2"; } } public override string Description { get { return "Cherry Soft PACK resource archive v2"; } } public override uint Signature { get { return 0x52454843; } } // 'CHER' public override bool IsHierarchic { get { return false; } } public override bool CanWrite { get { return false; } } public Pak2Opener () { Extensions = new string[] { "pak" }; } public override ArcFile TryOpen (ArcView file) { if (!file.View.AsciiEqual (0, "CHERRY PACK 2.0\0") && !file.View.AsciiEqual (0, "CHERRY PACK 3.0\0")) return null; int version = file.View.ReadByte (0xC) - '0'; bool is_compressed = file.View.ReadInt32 (0x10) != 0; int count = file.View.ReadInt32 (0x14); long base_offset = file.View.ReadUInt32 (0x18); bool is_encrypted = false; while (!IsSaneCount (count) || base_offset >= file.MaxOffset || (2 == version && !is_compressed && base_offset != (0x1C + count * 0x18))) { if (is_encrypted) return null; // these keys seem to be constant across different games count ^= unchecked((int)0xBC138744); base_offset ^= 0x64E0BA23; is_encrypted = true; } List<Entry> dir; if (is_compressed) { var packed = file.View.ReadBytes (0x1C, (uint)base_offset-0x1C); Decrypt (packed, 0, packed.Length); using (var mem = new MemoryStream (packed)) using (var lzss = new LzssStream (mem)) using (var index = new ArcView (lzss, file.Name, (uint)count * 0x18)) dir = ReadIndex (index, 0, count, base_offset, file); } else { dir = ReadIndex (file, 0x1C, count, base_offset, file); } if (null == dir) return null; if (is_encrypted && is_compressed) return new CherryPak (file, this, dir); else return new ArcFile (file, this, dir); } internal static void Decrypt (byte[] data, int index, int length) // Exile ~Blood Royal 2~ { for (int i = 0; i+1 < length; i += 2) { byte lo = (byte)(data[index+i ] ^ 0x33); byte hi = (byte)(data[index+i+1] ^ 0xCC); data[index+i ] = hi; data[index+i+1] = lo; } } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (!(arc is CherryPak) || entry.Size < 0x18) return base.OpenEntry (arc, entry); var data = arc.File.View.ReadBytes (entry.Offset, entry.Size); if (data.Length >= 0x18) { unsafe { fixed (byte* raw = data) { uint* raw32 = (uint*)raw; raw32[0] ^= 0xA53CC35Au; // FIXME: Exile-specific? raw32[1] ^= 0x35421005u; raw32[4] ^= 0xCF42355Du; } } Decrypt (data, 0x18, (int)(data.Length - 0x18)); } return new BinMemoryStream (data, entry.Name); } } }
namespace javax.microedition.khronos.egl { [global::MonoJavaBridge.JavaClass()] public static partial class EGL10Constants { public static int EGL_SUCCESS { get { return 12288; } } public static int EGL_NOT_INITIALIZED { get { return 12289; } } public static int EGL_BAD_ACCESS { get { return 12290; } } public static int EGL_BAD_ALLOC { get { return 12291; } } public static int EGL_BAD_ATTRIBUTE { get { return 12292; } } public static int EGL_BAD_CONFIG { get { return 12293; } } public static int EGL_BAD_CONTEXT { get { return 12294; } } public static int EGL_BAD_CURRENT_SURFACE { get { return 12295; } } public static int EGL_BAD_DISPLAY { get { return 12296; } } public static int EGL_BAD_MATCH { get { return 12297; } } public static int EGL_BAD_NATIVE_PIXMAP { get { return 12298; } } public static int EGL_BAD_NATIVE_WINDOW { get { return 12299; } } public static int EGL_BAD_PARAMETER { get { return 12300; } } public static int EGL_BAD_SURFACE { get { return 12301; } } public static int EGL_BUFFER_SIZE { get { return 12320; } } public static int EGL_ALPHA_SIZE { get { return 12321; } } public static int EGL_BLUE_SIZE { get { return 12322; } } public static int EGL_GREEN_SIZE { get { return 12323; } } public static int EGL_RED_SIZE { get { return 12324; } } public static int EGL_DEPTH_SIZE { get { return 12325; } } public static int EGL_STENCIL_SIZE { get { return 12326; } } public static int EGL_CONFIG_CAVEAT { get { return 12327; } } public static int EGL_CONFIG_ID { get { return 12328; } } public static int EGL_LEVEL { get { return 12329; } } public static int EGL_MAX_PBUFFER_HEIGHT { get { return 12330; } } public static int EGL_MAX_PBUFFER_PIXELS { get { return 12331; } } public static int EGL_MAX_PBUFFER_WIDTH { get { return 12332; } } public static int EGL_NATIVE_RENDERABLE { get { return 12333; } } public static int EGL_NATIVE_VISUAL_ID { get { return 12334; } } public static int EGL_NATIVE_VISUAL_TYPE { get { return 12335; } } public static int EGL_SAMPLES { get { return 12337; } } public static int EGL_SAMPLE_BUFFERS { get { return 12338; } } public static int EGL_SURFACE_TYPE { get { return 12339; } } public static int EGL_TRANSPARENT_TYPE { get { return 12340; } } public static int EGL_TRANSPARENT_BLUE_VALUE { get { return 12341; } } public static int EGL_TRANSPARENT_GREEN_VALUE { get { return 12342; } } public static int EGL_TRANSPARENT_RED_VALUE { get { return 12343; } } public static int EGL_NONE { get { return 12344; } } public static int EGL_LUMINANCE_SIZE { get { return 12349; } } public static int EGL_ALPHA_MASK_SIZE { get { return 12350; } } public static int EGL_COLOR_BUFFER_TYPE { get { return 12351; } } public static int EGL_RENDERABLE_TYPE { get { return 12352; } } public static int EGL_SLOW_CONFIG { get { return 12368; } } public static int EGL_NON_CONFORMANT_CONFIG { get { return 12369; } } public static int EGL_TRANSPARENT_RGB { get { return 12370; } } public static int EGL_RGB_BUFFER { get { return 12430; } } public static int EGL_LUMINANCE_BUFFER { get { return 12431; } } public static int EGL_VENDOR { get { return 12371; } } public static int EGL_VERSION { get { return 12372; } } public static int EGL_EXTENSIONS { get { return 12373; } } public static int EGL_HEIGHT { get { return 12374; } } public static int EGL_WIDTH { get { return 12375; } } public static int EGL_LARGEST_PBUFFER { get { return 12376; } } public static int EGL_RENDER_BUFFER { get { return 12422; } } public static int EGL_COLORSPACE { get { return 12423; } } public static int EGL_ALPHA_FORMAT { get { return 12424; } } public static int EGL_HORIZONTAL_RESOLUTION { get { return 12432; } } public static int EGL_VERTICAL_RESOLUTION { get { return 12433; } } public static int EGL_PIXEL_ASPECT_RATIO { get { return 12434; } } public static int EGL_SINGLE_BUFFER { get { return 12421; } } public static int EGL_CORE_NATIVE_ENGINE { get { return 12379; } } public static int EGL_DRAW { get { return 12377; } } public static int EGL_READ { get { return 12378; } } public static int EGL_DONT_CARE { get { return -1; } } public static int EGL_PBUFFER_BIT { get { return 1; } } public static int EGL_PIXMAP_BIT { get { return 2; } } public static int EGL_WINDOW_BIT { get { return 4; } } internal static global::MonoJavaBridge.FieldId _EGL_DEFAULT_DISPLAY6991; public static global::java.lang.Object EGL_DEFAULT_DISPLAY { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::javax.microedition.khronos.egl.EGL10_.staticClass, _EGL_DEFAULT_DISPLAY6991)) as java.lang.Object; } } internal static global::MonoJavaBridge.FieldId _EGL_NO_DISPLAY6992; public static global::javax.microedition.khronos.egl.EGLDisplay EGL_NO_DISPLAY { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::javax.microedition.khronos.egl.EGL10_.staticClass, _EGL_NO_DISPLAY6992)) as javax.microedition.khronos.egl.EGLDisplay; } } internal static global::MonoJavaBridge.FieldId _EGL_NO_CONTEXT6993; public static global::javax.microedition.khronos.egl.EGLContext EGL_NO_CONTEXT { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::javax.microedition.khronos.egl.EGL10_.staticClass, _EGL_NO_CONTEXT6993)) as javax.microedition.khronos.egl.EGLContext; } } internal static global::MonoJavaBridge.FieldId _EGL_NO_SURFACE6994; public static global::javax.microedition.khronos.egl.EGLSurface EGL_NO_SURFACE { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetStaticObjectField(global::javax.microedition.khronos.egl.EGL10_.staticClass, _EGL_NO_SURFACE6994)) as javax.microedition.khronos.egl.EGLSurface; } } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace SharpDX.Animation { public partial class Manager { private static readonly Guid ManagerGuid = new Guid("4C1FC63A-695C-47E8-A339-1A194BE3D0B8"); private ManagerEventHandlerShadow shadowEventHandler; /// <summary> /// Initializes a new instance of the <see cref="Manager"/> class. /// </summary> public Manager() { Utilities.CreateComInstance(ManagerGuid, Utilities.CLSCTX.ClsctxInprocServer, Utilities.GetGuidFromType(typeof(Manager)), this); } /// <summary> /// A delegate to receive status changed events from the manager. /// </summary> /// <param name="newStatus">The new status.</param> /// <param name="previousStatus">The previous status.</param> public delegate void StatusChangedDelegate(ManagerStatus newStatus, ManagerStatus previousStatus); /// <summary> /// A delegate used to resolve scheduling conflicts. /// </summary> /// <param name="scheduledStoryboard">The scheduled storyboard.</param> /// <param name="newStoryboard">The new storyboard.</param> /// <param name="priorityEffect">The priority effect.</param> /// <returns><c>true</c> if newStoryboard has priority. <c>false</c> if scheduledStoryboard has priority</returns> public delegate bool PriorityComparisonDelegate(Storyboard scheduledStoryboard, Storyboard newStoryboard, PriorityEffect priorityEffect); /// <summary> /// Occurs when [status changed]. /// </summary> public event StatusChangedDelegate StatusChanged { add { // Setup the Manager Event Handler delegates if (shadowEventHandler == null) { shadowEventHandler = new ManagerEventHandlerShadow(); SetManagerEventHandler_(ManagerEventHandlerShadow.ToIntPtr(shadowEventHandler)); } shadowEventHandler.Delegates += value; } remove { if (shadowEventHandler == null) return; shadowEventHandler.Delegates -= value; if (shadowEventHandler.Delegates.GetInvocationList().Length == 0) { SetManagerEventHandler_(IntPtr.Zero); shadowEventHandler.Dispose(); shadowEventHandler = null; } } } private PriorityComparisonShadow cancelPriorityComparisonShadow; /// <summary> /// Sets the cancel priority comparison. /// </summary> /// <value> /// The cancel priority comparison. /// </value> public PriorityComparisonDelegate CancelPriorityComparison { set { if (value != null) { if (cancelPriorityComparisonShadow == null) { cancelPriorityComparisonShadow = new PriorityComparisonShadow { Delegate = value }; SetCancelPriorityComparison_(PriorityComparisonShadow.ToIntPtr(cancelPriorityComparisonShadow)); } cancelPriorityComparisonShadow.Delegate = value; } else if (cancelPriorityComparisonShadow != null) { SetCancelPriorityComparison_(IntPtr.Zero); cancelPriorityComparisonShadow.Dispose(); cancelPriorityComparisonShadow = null; } } } private PriorityComparisonShadow trimPriorityComparisonShadow; /// <summary> /// Sets the trim priority comparison. /// </summary> /// <value> /// The trim priority comparison. /// </value> public PriorityComparisonDelegate TrimPriorityComparison { set { if (value != null) { if (trimPriorityComparisonShadow == null) { trimPriorityComparisonShadow = new PriorityComparisonShadow { Delegate = value }; SetTrimPriorityComparison_(PriorityComparisonShadow.ToIntPtr(trimPriorityComparisonShadow)); } trimPriorityComparisonShadow.Delegate = value; } else if (trimPriorityComparisonShadow != null) { SetTrimPriorityComparison_(IntPtr.Zero); trimPriorityComparisonShadow.Dispose(); trimPriorityComparisonShadow = null; } } } private PriorityComparisonShadow compressPriorityComparisonShadow; /// <summary> /// Sets the compress priority comparison. /// </summary> /// <value> /// The compress priority comparison. /// </value> public PriorityComparisonDelegate CompressPriorityComparison { set { if (value != null) { if (compressPriorityComparisonShadow == null) { compressPriorityComparisonShadow = new PriorityComparisonShadow { Delegate = value }; SetCompressPriorityComparison_(PriorityComparisonShadow.ToIntPtr(compressPriorityComparisonShadow)); } compressPriorityComparisonShadow.Delegate = value; } else if (compressPriorityComparisonShadow != null) { SetCompressPriorityComparison_(IntPtr.Zero); compressPriorityComparisonShadow.Dispose(); compressPriorityComparisonShadow = null; } } } private PriorityComparisonShadow concludePriorityComparisonShadow; /// <summary> /// Sets the conclude priority comparison. /// </summary> /// <value> /// The conclude priority comparison. /// </value> public PriorityComparisonDelegate ConcludePriorityComparison { set { if (value != null) { if (trimPriorityComparisonShadow == null) { trimPriorityComparisonShadow = new PriorityComparisonShadow { Delegate = value }; SetConcludePriorityComparison_(PriorityComparisonShadow.ToIntPtr(trimPriorityComparisonShadow)); } trimPriorityComparisonShadow.Delegate = value; } else if (trimPriorityComparisonShadow != null) { SetConcludePriorityComparison_(IntPtr.Zero); trimPriorityComparisonShadow.Dispose(); trimPriorityComparisonShadow = null; } } } /// <summary> /// Gets the variable from tag. /// </summary> /// <param name="id">The id.</param> /// <param name="tagObject">The tag object. This parameter can be null.</param> /// <returns>A variable associated with this tag.</returns> /// <unmanaged>HRESULT IUIAnimationManager::GetVariableFromTag([In, Optional] void* object,[In] unsigned int id,[Out] IUIAnimationVariable** variable)</unmanaged> public SharpDX.Animation.Variable GetVariableFromTag(int id, object tagObject = null) { var tagObjectHandle = GCHandle.Alloc(tagObject); try { return GetVariableFromTag(GCHandle.ToIntPtr(tagObjectHandle), id); } finally { tagObjectHandle.Free(); } } /// <summary> /// Gets the storyboard from tag. /// </summary> /// <param name="id">The id.</param> /// <param name="tagObject">The tag object. This parameter can be null.</param> /// <returns>A storyboard associated with this tag.</returns> /// <unmanaged>HRESULT IUIAnimationManager::GetStoryboardFromTag([In, Optional] void* object,[In] unsigned int id,[Out] IUIAnimationStoryboard** storyboard)</unmanaged> public SharpDX.Animation.Storyboard GetStoryboardFromTag(int id, object tagObject = null) { var tagObjectHandle = GCHandle.Alloc(tagObject); try { return GetStoryboardFromTag(GCHandle.ToIntPtr(tagObjectHandle), id); } finally { tagObjectHandle.Free(); } } /// <inheritdoc/> protected override void Dispose(bool disposing) { if (shadowEventHandler != null) { SetManagerEventHandler_(IntPtr.Zero); shadowEventHandler.Dispose(); shadowEventHandler = null; } if (cancelPriorityComparisonShadow != null) { SetCancelPriorityComparison_(IntPtr.Zero); cancelPriorityComparisonShadow.Dispose(); cancelPriorityComparisonShadow = null; } if (trimPriorityComparisonShadow != null) { SetConcludePriorityComparison_(IntPtr.Zero); trimPriorityComparisonShadow.Dispose(); trimPriorityComparisonShadow = null; } if (compressPriorityComparisonShadow != null) { SetCompressPriorityComparison_(IntPtr.Zero); compressPriorityComparisonShadow.Dispose(); compressPriorityComparisonShadow = null; } if (trimPriorityComparisonShadow != null) { SetConcludePriorityComparison_(IntPtr.Zero); trimPriorityComparisonShadow.Dispose(); trimPriorityComparisonShadow = null; } base.Dispose(disposing); } } }
/* * 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 System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using Aurora.Framework.Serialization; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace Aurora.Modules.Startup { public class Backup : ISharedRegionStartupModule { #region Declares protected SceneManager m_manager; protected Dictionary<IScene, InternalSceneBackup> m_backup = new Dictionary<IScene, InternalSceneBackup>(); // the minimum time that must elapse before a changed object will be considered for persisted public static long m_dontPersistBefore = 60; // the maximum time that must elapse before a changed object will be considered for persisted public static long m_persistAfter = 600; #endregion #region ISharedRegionStartupModule Members public void Initialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { if (MainConsole.Instance != null && m_backup.Count == 0)//Only add them once { MainConsole.Instance.Commands.AddCommand ("backup", "backup", "Persist objects to the database now, if [all], will force the persistence of all prims", RunCommand); MainConsole.Instance.Commands.AddCommand ("disable backup", "disable backup", "Disables persistance until reenabled", DisableBackup); MainConsole.Instance.Commands.AddCommand ("enable backup", "disable backup", "Enables persistance after 'disable persistance' has been run", EnableBackup); } //Set up the backup for the scene m_backup[scene] = new InternalSceneBackup(scene); IConfig persistanceConfig = source.Configs["Persistance"]; if (persistanceConfig != null) { m_dontPersistBefore = persistanceConfig.GetLong("MinimumTimeBeforePersistenceConsidered", m_dontPersistBefore); m_persistAfter = persistanceConfig.GetLong("MaximumTimeBeforePersistenceConsidered", m_persistAfter); } } public void PostInitialise(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void FinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { } public void PostFinishStartup(IScene scene, IConfigSource source, ISimulationBase openSimBase) { m_manager = scene.RequestModuleInterface<SceneManager>(); m_backup[scene].FinishStartup(); } public void StartupComplete() { EnableBackup (null); } public void Close(IScene scene) { m_backup.Remove(scene); } public void DeleteRegion(IScene scene) { } #endregion #region Console commands /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand (string[] cmdparams) { #if (!ISWIN) m_manager.ForEachCurrentScene(delegate(IScene scene) { scene.AuroraEventManager.FireGenericEventHandler("Backup", null); }); #else m_manager.ForEachCurrentScene (scene => scene.AuroraEventManager.FireGenericEventHandler("Backup", null)); #endif } public void DisableBackup (string[] cmdparams) { m_manager.ForEachCurrentScene (delegate (IScene scene) { scene.SimulationDataService.SaveBackups = false; }); MainConsole.Instance.Warn ("Disabled backup"); } public void EnableBackup (string[] cmdparams) { m_manager.ForEachCurrentScene (delegate (IScene scene) { scene.SimulationDataService.SaveBackups = true; }); if(cmdparams != null)//so that it doesn't show on startup MainConsole.Instance.Warn ("Enabled backup"); } #endregion #region Per region backup class protected class InternalSceneBackup : IBackupModule, IAuroraBackupModule { #region Declares protected IScene m_scene; protected bool m_LoadingPrims; #endregion #region Constructor public InternalSceneBackup (IScene scene) { m_scene = scene; m_scene.StackModuleInterface<IAuroraBackupModule> (this); m_scene.RegisterModuleInterface<IBackupModule> (this); if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand ("delete object owner", "delete object owner <UUID>", "Delete object by owner", HandleDeleteObject); MainConsole.Instance.Commands.AddCommand ("delete object creator", "delete object creator <UUID>", "Delete object by creator", HandleDeleteObject); MainConsole.Instance.Commands.AddCommand ("delete object uuid", "delete object uuid <UUID>", "Delete object by uuid", HandleDeleteObject); MainConsole.Instance.Commands.AddCommand ("delete object name", "delete object name <name>", "Delete object by name", HandleDeleteObject); } } #endregion #region Console Commands private void HandleDeleteObject (string[] cmd) { if (cmd.Length < 4) return; string mode = cmd[2]; string o = cmd[3]; List<ISceneEntity> deletes = new List<ISceneEntity> (); UUID match; switch (mode) { case "owner": if (!UUID.TryParse (o, out match)) return; m_scene.ForEachSceneEntity (delegate (ISceneEntity g) { if (g.OwnerID == match && !g.IsAttachment) deletes.Add (g); }); break; case "creator": if (!UUID.TryParse (o, out match)) return; m_scene.ForEachSceneEntity (delegate (ISceneEntity g) { if (g.RootChild.CreatorID == match && !g.IsAttachment) deletes.Add (g); }); break; case "uuid": if (!UUID.TryParse (o, out match)) return; m_scene.ForEachSceneEntity (delegate (ISceneEntity g) { if (g.UUID == match && !g.IsAttachment) deletes.Add (g); }); break; case "name": m_scene.ForEachSceneEntity (delegate (ISceneEntity g) { if (g.RootChild.Name == o && !g.IsAttachment) deletes.Add (g); }); break; } MainConsole.Instance.Warn("Deleting " + deletes.Count + " objects."); DeleteSceneObjects(deletes.ToArray(), true, true); } #endregion #region Scene events /// <summary> /// Loads the World's objects /// </summary> public void LoadPrimsFromStorage() { LoadingPrims = true; MainConsole.Instance.Info("[BackupModule]: Loading objects for " + m_scene.RegionInfo.RegionName); List<ISceneEntity> PrimsFromDB = m_scene.SimulationDataService.LoadObjects(m_scene); foreach (ISceneEntity group in PrimsFromDB) { try { if (group.IsAttachment || (group.RootChild.Shape != null && (group.RootChild.Shape.State != 0 && (group.RootChild.Shape.PCode == (byte)PCode.None || group.RootChild.Shape.PCode == (byte)PCode.Prim || group.RootChild.Shape.PCode == (byte)PCode.Avatar)))) { MainConsole.Instance.Warn("[BackupModule]: Broken state for object " + group.Name + " while loading objects, removing it from the database."); //WTF went wrong here? Remove by passing it by on loading continue; } if (group.RootChild.Shape == null) { MainConsole.Instance.Warn("[BackupModule]: Broken object (" + group.Name + ") found while loading objects, removing it from the database."); //WTF went wrong here? Remove by passing it by on loading continue; } if (group.AbsolutePosition.X > m_scene.RegionInfo.RegionSizeX + 10 || group.AbsolutePosition.X < -10 || group.AbsolutePosition.Y > m_scene.RegionInfo.RegionSizeY + 10 || group.AbsolutePosition.Y < -10) { MainConsole.Instance.Warn ("[BackupModule]: Object outside the region (" + group.Name + ", " + group.AbsolutePosition + ") found while loading objects, removing it from the database."); //WTF went wrong here? Remove by passing it by on loading continue; } m_scene.SceneGraph.CheckAllocationOfLocalIds (group); group.Scene = m_scene; if (group.RootChild == null) { MainConsole.Instance.ErrorFormat("[BackupModule] Found a SceneObjectGroup with m_rootPart == null and {0} children", group.ChildrenEntities().Count); continue; } m_scene.SceneGraph.RestorePrimToScene(group, false); } catch(Exception ex) { MainConsole.Instance.WarnFormat("[BackupModule]: Exception attempting to load object from the database, {0}, continuing...", ex.ToString()); } } LoadingPrims = false; MainConsole.Instance.Info("[BackupModule]: Loaded " + PrimsFromDB.Count.ToString() + " object(s) in " + m_scene.RegionInfo.RegionName); PrimsFromDB.Clear (); } /// <summary> /// Loads all Parcel data from the datastore for region identified by regionID /// </summary> public void LoadAllLandObjectsFromStorage() { MainConsole.Instance.Debug ("[BackupModule]: Loading Land Objects from database... "); m_scene.EventManager.TriggerIncomingLandDataFromStorage(m_scene.SimulationDataService.LoadLandObjects(m_scene.RegionInfo.RegionID), Vector2.Zero); } public void FinishStartup() { //Load the prims from the database now that we are done loading LoadPrimsFromStorage(); //Then load the land objects LoadAllLandObjectsFromStorage(); //Load the prims from the database now that we are done loading CreateScriptInstances(); } /// <summary> /// Start all the scripts in the scene which should be started. /// </summary> public void CreateScriptInstances() { MainConsole.Instance.Info("[BackupModule]: Starting scripts in " + m_scene.RegionInfo.RegionName); //Set loading prims here to block backup LoadingPrims = true; ISceneEntity[] entities = m_scene.Entities.GetEntities(); foreach(ISceneEntity group in entities) { group.CreateScriptInstances(0, false, StateSource.RegionStart, UUID.Zero); } //Now reset it LoadingPrims = false; } #endregion #region Public members /// <summary> /// Are we currently loading prims? /// </summary> public bool LoadingPrims { get { return m_LoadingPrims; } set { m_LoadingPrims = value; } } /// <summary> /// Delete every object from the scene. This does not include attachments worn by avatars. /// </summary> public void DeleteAllSceneObjects() { try { LoadingPrims = true; List<ISceneEntity> groups = new List<ISceneEntity>(); lock (m_scene.Entities) { ISceneEntity[] entities = m_scene.Entities.GetEntities(); #if (!ISWIN) foreach (ISceneEntity entity in entities) { if (!entity.IsAttachment) groups.Add(entity); } #else groups.AddRange(entities.Where(entity => !entity.IsAttachment)); #endif } //Delete all the groups now DeleteSceneObjects(groups.ToArray(), true, true); //Now remove the entire region at once m_scene.SimulationDataService.RemoveRegion(m_scene.RegionInfo.RegionID); LoadingPrims = false; } catch { } } public void ResetRegionToStartupDefault () { //Add the loading prims piece just to be safe LoadingPrims = true; try { lock (m_scene.Entities) { ISceneEntity[] entities = m_scene.Entities.GetEntities(); foreach (ISceneEntity entity in entities) { if (!entity.IsAttachment) { List<ISceneChildEntity> parts = new List<ISceneChildEntity>(); parts.AddRange(entity.ChildrenEntities()); DeleteSceneObject(entity, true, false); //Don't remove from the database #if (!ISWIN) m_scene.ForEachScenePresence(delegate(IScenePresence avatar) { avatar.ControllingClient.SendKillObject(m_scene.RegionInfo.RegionHandle, parts.ToArray()); }); #else m_scene.ForEachScenePresence( avatar => avatar.ControllingClient.SendKillObject(m_scene.RegionInfo.RegionHandle, parts.ToArray())); #endif } } } } catch { } LoadingPrims = false; } /// <summary> /// Synchronously delete the objects from the scene. /// This does send kill object updates and resets the parcel prim counts. /// </summary> /// <param name="groups"></param> /// <param name="DeleteScripts"></param> /// <param name="sendKillPackets"></param> /// <returns></returns> public bool DeleteSceneObjects (ISceneEntity[] groups, bool DeleteScripts, bool sendKillPackets) { List<ISceneChildEntity> parts = new List<ISceneChildEntity>(); foreach (ISceneEntity grp in groups) { if (grp == null) continue; //if (group.IsAttachment) // continue; parts.AddRange(grp.ChildrenEntities()); DeleteSceneObject(grp, true, true); } if(sendKillPackets) { #if (!ISWIN) m_scene.ForEachScenePresence(delegate(IScenePresence avatar) { avatar.ControllingClient.SendKillObject( m_scene.RegionInfo.RegionHandle, parts.ToArray()); }); #else m_scene.ForEachScenePresence(avatar => avatar.ControllingClient.SendKillObject( m_scene.RegionInfo.RegionHandle, parts.ToArray())); #endif } return true; } /// <summary> /// Add a backup taint to the prim /// </summary> /// <param name="sceneObjectGroup"></param> public void AddPrimBackupTaint (ISceneEntity sceneObjectGroup) { //Tell the database that something has changed m_scene.SimulationDataService.Tainted (); } #endregion #region Per Object Methods /// <summary> /// Synchronously delete the given object from the scene. /// </summary> /// <param name="group">Object Id</param> /// <param name="DeleteScripts">Remove the scripts from the ScriptEngine as well</param> /// <param name="removeFromDatabase">Remove from the database?</param> protected bool DeleteSceneObject(ISceneEntity group, bool DeleteScripts, bool removeFromDatabase) { //MainConsole.Instance.DebugFormat("[Backup]: Deleting scene object {0} {1}", group.Name, group.UUID); lock (group.SitTargetAvatar) { if (group.SitTargetAvatar.Count != 0) { UUID[] ids = new UUID[group.SitTargetAvatar.Count]; group.SitTargetAvatar.CopyTo(ids); foreach (UUID avID in ids) { //Don't screw up avatar's that are sitting on us! IScenePresence SP = m_scene.GetScenePresence(avID); if (SP != null) SP.StandUp(); } } } // Serialise calls to RemoveScriptInstances to avoid // deadlocking on m_parts inside SceneObjectGroup if (DeleteScripts) { group.RemoveScriptInstances(true); } foreach (ISceneChildEntity part in group.ChildrenEntities()) { IScriptControllerModule m = m_scene.RequestModuleInterface<IScriptControllerModule>(); if(m != null) m.RemoveAllScriptControllers(part); } if (group.RootChild.PhysActor != null) { //Remove us from the physics sim m_scene.PhysicsScene.DeletePrim(group.RootChild.PhysActor); //We MUST leave this to the PhysicsScene or it will hate us forever! //group.RootChild.PhysActor = null; } if(!group.IsAttachment) m_scene.SimulationDataService.Tainted (); if (m_scene.SceneGraph.DeleteEntity(group)) { // We need to keep track of this state in case this group is still queued for backup. group.IsDeleted = true; m_scene.EventManager.TriggerObjectBeingRemovedFromScene(group); return true; } //MainConsole.Instance.DebugFormat("[SCENE]: Exit DeleteSceneObject() for {0} {1}", group.Name, group.UUID); return false; } #endregion #region IAuroraBackupModule Methods private bool m_isArchiving = false; private readonly List<UUID> m_missingAssets = new List<UUID>(); private readonly List<LandData> m_parcels = new List<LandData>(); private bool m_merge = false; private bool m_loadAssets = false; private GenericAccountCache<OpenSim.Services.Interfaces.UserAccount> m_cache = new GenericAccountCache<OpenSim.Services.Interfaces.UserAccount>(); private List<SceneObjectGroup> m_groups = new List<SceneObjectGroup>(); public bool IsArchiving { get { return m_isArchiving; } } public void SaveModuleToArchive(TarArchiveWriter writer, IScene scene) { m_isArchiving = true; MainConsole.Instance.Info("[Archive]: Writing parcels to archive"); writer.WriteDir("parcels"); IParcelManagementModule module = scene.RequestModuleInterface<IParcelManagementModule>(); if (module != null) { List<ILandObject> landObject = module.AllParcels(); foreach (ILandObject parcel in landObject) { OSDMap parcelMap = parcel.LandData.ToOSD(); writer.WriteFile("parcels/" + parcel.LandData.GlobalID.ToString(), OSDParser.SerializeLLSDBinary(parcelMap)); parcelMap = null; } } MainConsole.Instance.Info("[Archive]: Finished writing parcels to archive"); MainConsole.Instance.Info ("[Archive]: Writing terrain to archive"); writer.WriteDir ("newstyleterrain"); writer.WriteDir ("newstylerevertterrain"); writer.WriteDir ("newstylewater"); writer.WriteDir ("newstylerevertwater"); ITerrainModule tModule = scene.RequestModuleInterface<ITerrainModule> (); if (tModule != null) { try { byte[] sdata = WriteTerrainToStream (tModule.TerrainMap); writer.WriteFile ("newstyleterrain/" + scene.RegionInfo.RegionID.ToString () + ".terrain", sdata); sdata = null; sdata = WriteTerrainToStream (tModule.TerrainRevertMap); writer.WriteFile ("newstylerevertterrain/" + scene.RegionInfo.RegionID.ToString () + ".terrain", sdata); sdata = null; if (tModule.TerrainWaterMap != null) { sdata = WriteTerrainToStream (tModule.TerrainWaterMap); writer.WriteFile ("newstylewater/" + scene.RegionInfo.RegionID.ToString () + ".terrain", sdata); sdata = null; sdata = WriteTerrainToStream (tModule.TerrainWaterRevertMap); writer.WriteFile ("newstylerevertwater/" + scene.RegionInfo.RegionID.ToString () + ".terrain", sdata); sdata = null; } } catch (Exception ex) { MainConsole.Instance.WarnFormat ("[Backup]: Exception caught: {0}", ex.ToString ()); } } MainConsole.Instance.Info("[Archive]: Finished writing terrain to archive"); MainConsole.Instance.Info("[Archive]: Writing entities to archive"); ISceneEntity[] entities = scene.Entities.GetEntities(); //Get all entities, then start writing them to the database writer.WriteDir("entities"); IDictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>(); UuidGatherer assetGatherer = new UuidGatherer(m_scene.AssetService); IAuroraBackupArchiver archiver = m_scene.RequestModuleInterface<IAuroraBackupArchiver> (); bool saveAssets = false; if(archiver.AllowPrompting) saveAssets = MainConsole.Instance.Prompt ("Save assets? (Will not be able to load on other grids)", "false").Equals ("true", StringComparison.CurrentCultureIgnoreCase); int count = 0; foreach (ISceneEntity entity in entities) { try { if (entity.IsAttachment || ((entity.RootChild.Flags & PrimFlags.Temporary) == PrimFlags.Temporary) || ((entity.RootChild.Flags & PrimFlags.TemporaryOnRez) == PrimFlags.TemporaryOnRez)) continue; //Write all entities byte[] xml = ((ISceneObject)entity).ToBinaryXml2 (); writer.WriteFile ("entities/" + entity.UUID.ToString (), xml); xml = null; count++; if (count % 5 == 0) Thread.Sleep (1); //Get all the assets too if (saveAssets) assetGatherer.GatherAssetUuids (entity, assets, scene); } catch (Exception ex) { MainConsole.Instance.WarnFormat ("[Backup]: Exception caught: {0}", ex); } } entities = null; MainConsole.Instance.Info("[Archive]: Finished writing entities to archive"); MainConsole.Instance.Info("[Archive]: Writing assets for entities to archive"); bool foundAllAssets = true; foreach (UUID assetID in new List<UUID> (assets.Keys)) { try { foundAllAssets = false; //Not all are cached m_scene.AssetService.Get (assetID.ToString (), writer, RetrievedAsset); m_missingAssets.Add(assetID); } catch (Exception ex) { MainConsole.Instance.WarnFormat ("[Backup]: Exception caught: {0}", ex); } } if (foundAllAssets) m_isArchiving = false; //We're done if all the assets were found MainConsole.Instance.Info("[Archive]: Finished writing assets for entities to archive"); } private static byte[] WriteTerrainToStream (ITerrainChannel tModule) { int tMapSize = tModule.Height * tModule.Height; byte[] sdata = new byte[tMapSize * 2]; Buffer.BlockCopy (tModule.GetSerialised (tModule.Scene), 0, sdata, 0, sdata.Length); return sdata; } private void RetrievedAsset(string id, Object sender, AssetBase asset) { TarArchiveWriter writer = (TarArchiveWriter)sender; //Add the asset WriteAsset(id, asset, writer); m_missingAssets.Remove(UUID.Parse(id)); if (m_missingAssets.Count == 0) m_isArchiving = false; } private void WriteAsset(string id, AssetBase asset, TarArchiveWriter writer) { if (asset != null) writer.WriteFile ("assets/" + asset.ID, OSDParser.SerializeJsonString(asset.ToOSD())); else MainConsole.Instance.WarnFormat ("Could not find asset {0}", id); } public void BeginLoadModuleFromArchive(IScene scene) { IBackupModule backup = scene.RequestModuleInterface<IBackupModule>(); IScriptModule[] modules = scene.RequestModuleInterfaces<IScriptModule>(); IParcelManagementModule parcelModule = scene.RequestModuleInterface<IParcelManagementModule>(); //Disable the script engine so that it doesn't load in the background and kill OAR loading foreach (IScriptModule module in modules) { if(module != null) module.Disabled = true; } //Disable backup for now as well if (backup != null) { backup.LoadingPrims = true; m_loadAssets = MainConsole.Instance.Prompt("Should any stored assets be loaded? (If you got this .abackup from another grid, choose yes", "no").ToLower() == "yes"; m_merge = MainConsole.Instance.Prompt("Should we merge prims together (keep the prims from the old region too)?", "no").ToLower() == "yes"; if (!m_merge) { DateTime before = DateTime.Now; MainConsole.Instance.Info("[ARCHIVER]: Clearing all existing scene objects"); backup.DeleteAllSceneObjects(); MainConsole.Instance.Info("[ARCHIVER]: Cleared all existing scene objects in " + (DateTime.Now - before).Minutes + ":" + (DateTime.Now - before).Seconds); if (parcelModule != null) parcelModule.ClearAllParcels (); } } } public void EndLoadModuleFromArchive(IScene scene) { IBackupModule backup = scene.RequestModuleInterface<IBackupModule>(); IScriptModule[] modules = scene.RequestModuleInterfaces<IScriptModule>(); //Reeanble now that we are done foreach (IScriptModule module in modules) { module.Disabled = false; } //Reset backup too if (backup != null) backup.LoadingPrims = false; //Update the database as well! IParcelManagementModule parcelManagementModule = scene.RequestModuleInterface<IParcelManagementModule>(); if (parcelManagementModule != null && !m_merge) //Only if we are not merging { if (m_parcels.Count > 0) { scene.EventManager.TriggerIncomingLandDataFromStorage(m_parcels, Vector2.Zero); //Update the database as well! foreach (LandData parcel in m_parcels) { parcelManagementModule.UpdateLandObject(parcelManagementModule.GetLandObject(parcel.LocalID)); } } else parcelManagementModule.ResetSimLandObjects (); m_parcels.Clear(); } foreach (SceneObjectGroup sceneObject in m_groups) { foreach (ISceneChildEntity part in sceneObject.ChildrenEntities()) { if (!ResolveUserUuid(part.CreatorID)) part.CreatorID = m_scene.RegionInfo.EstateSettings.EstateOwner; if (!ResolveUserUuid(part.OwnerID)) part.OwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; if (!ResolveUserUuid(part.LastOwnerID)) part.LastOwnerID = m_scene.RegionInfo.EstateSettings.EstateOwner; // Fix ownership/creator of inventory items // Not doing so results in inventory items // being no copy/no mod for everyone lock (part.TaskInventory) { TaskInventoryDictionary inv = part.TaskInventory; foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv) { if (!ResolveUserUuid(kvp.Value.OwnerID)) { kvp.Value.OwnerID = scene.RegionInfo.EstateSettings.EstateOwner; } if (!ResolveUserUuid(kvp.Value.CreatorID)) { kvp.Value.CreatorID = scene.RegionInfo.EstateSettings.EstateOwner; } } } } if (scene.SceneGraph.AddPrimToScene(sceneObject)) { sceneObject.HasGroupChanged = true; sceneObject.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate); sceneObject.CreateScriptInstances(0, false, StateSource.RegionStart, UUID.Zero); } } } public void LoadModuleFromArchive(byte[] data, string filePath, TarArchiveReader.TarEntryType type, IScene scene) { if (filePath.StartsWith("parcels/")) { if (!m_merge) { //Only use if we are not merging LandData parcel = new LandData(); OSD parcelData = OSDParser.DeserializeLLSDBinary(data); parcel.FromOSD((OSDMap)parcelData); m_parcels.Add(parcel); } } #region New Style Terrain Loading else if (filePath.StartsWith ("newstyleterrain/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); terrainModule.TerrainMap = ReadTerrain(data, scene); } else if (filePath.StartsWith ("newstylerevertterrain/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); terrainModule.TerrainRevertMap = ReadTerrain(data, scene); } else if (filePath.StartsWith ("newstylewater/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); terrainModule.TerrainWaterMap = ReadTerrain(data, scene); } else if (filePath.StartsWith ("newstylerevertwater/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); terrainModule.TerrainWaterRevertMap = ReadTerrain(data, scene); } #endregion #region Old Style Terrain Loading else if (filePath.StartsWith ("terrain/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream (data); terrainModule.LoadFromStream (filePath, ms, 0, 0); ms.Close (); } else if (filePath.StartsWith ("revertterrain/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream (data); terrainModule.LoadRevertMapFromStream (filePath, ms, 0, 0); ms.Close (); } else if (filePath.StartsWith ("water/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream (data); terrainModule.LoadWaterFromStream (filePath, ms, 0, 0); ms.Close (); } else if (filePath.StartsWith ("revertwater/")) { ITerrainModule terrainModule = scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream (data); terrainModule.LoadWaterRevertMapFromStream (filePath, ms, 0, 0); ms.Close (); } #endregion else if (filePath.StartsWith ("entities/")) { MemoryStream ms = new MemoryStream (data); SceneObjectGroup sceneObject = OpenSim.Region.Framework.Scenes.Serialization.SceneObjectSerializer.FromXml2Format (ref ms, scene); ms.Close (); ms = null; data = null; m_groups.Add(sceneObject); } else if(filePath.StartsWith("assets/")) { if(m_loadAssets) { AssetBase asset = new AssetBase(); asset.Unpack(OSDParser.DeserializeJson(Encoding.UTF8.GetString(data))); scene.AssetService.Store(asset); } } } private ITerrainChannel ReadTerrain (byte[] data, IScene scene) { short[] sdata = new short[data.Length / 2]; Buffer.BlockCopy (data, 0, sdata, 0, data.Length); return new TerrainChannel(sdata, scene); } private bool ResolveUserUuid (UUID uuid) { OpenSim.Services.Interfaces.UserAccount acc; if (m_cache.Get(uuid, out acc)) return acc != null; acc = m_scene.UserAccountService.GetUserAccount (m_scene.RegionInfo.ScopeID, uuid); m_cache.Cache(uuid, acc); return acc != null; } #endregion } #endregion } }
/* * C# port of Mozilla Character Set Detector * https://code.google.com/p/chardetsharp/ * * Original Mozilla License Block follows * */ #region License Block // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // The Original Code is Mozilla Universal charset detector code. // // The Initial Developer of the Original Code is // Simon Montagu <smontagu@smontagu.org> // Portions created by the Initial Developer are Copyright (C) 2005 // the Initial Developer. All Rights Reserved. // // Contributor(s): // Shoshannah Forbes <xslf@xslf.com> // Shy Shalom <shooshX@gmail.com> // // Alternatively, the contents of this file may be used under the terms of // either the GNU General Public License Version 2 or later (the "GPL"), or // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), // in which case the provisions of the GPL or the LGPL are applicable instead // of those above. If you wish to allow use of your version of this file only // under the terms of either the GPL or the LGPL, and not to allow others to // use your version of this file under the terms of the MPL, indicate your // decision by deleting the provisions above and replace them with the notice // and other provisions required by the GPL or the LGPL. If you do not delete // the provisions above, a recipient may use your version of this file under // the terms of any one of the MPL, the GPL or the LGPL. #endregion namespace Cloney.Core.CharsetDetection { internal partial class SequenceModel { //***************************************************************** // 255: Control characters that usually does not exist in any text // 254: Carriage/Return // 253: symbol (punctuation) that does not belong to word // 252: 0 - 9 //***************************************************************** static readonly byte[] win1255_CharToOrderMap = new byte[] { 255,255,255,255,255,255,255,255,255,255,254,255,255,254,255,255, //00 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, //10 253,253,253,253,253,253,253,253,253,253,253,253,253,253,253,253, //20 252,252,252,252,252,252,252,252,252,252,253,253,253,253,253,253, //30 253, 69, 91, 79, 80, 92, 89, 97, 90, 68,111,112, 82, 73, 95, 85, //40 78,121, 86, 71, 67,102,107, 84,114,103,115,253,253,253,253,253, //50 253, 50, 74, 60, 61, 42, 76, 70, 64, 53,105, 93, 56, 65, 54, 49, //60 66,110, 51, 43, 44, 63, 81, 77, 98, 75,108,253,253,253,253,253, //70 124,202,203,204,205, 40, 58,206,207,208,209,210,211,212,213,214, 215, 83, 52, 47, 46, 72, 32, 94,216,113,217,109,218,219,220,221, 34,116,222,118,100,223,224,117,119,104,125,225,226, 87, 99,227, 106,122,123,228, 55,229,230,101,231,232,120,233, 48, 39, 57,234, 30, 59, 41, 88, 33, 37, 36, 31, 29, 35,235, 62, 28,236,126,237, 238, 38, 45,239,240,241,242,243,127,244,245,246,247,248,249,250, 9, 8, 20, 16, 3, 2, 24, 14, 22, 1, 25, 15, 4, 11, 6, 23, 12, 19, 13, 26, 18, 27, 21, 17, 7, 10, 5,251,252,128, 96,253, }; //Model Table: //total sequences: 100% //first 512 sequences: 98.4004% //first 1024 sequences: 1.5981% //rest sequences: 0.087% //negative sequences: 0.0015% static readonly byte[] HebrewLangModel = new byte[] { 0,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,2,3,2,1,2,0,1,0,0, 3,0,3,1,0,0,1,3,2,0,1,1,2,0,2,2,2,1,1,1,1,2,1,1,1,2,0,0,2,2,0,1, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2, 1,2,1,2,1,2,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2, 1,2,1,3,1,1,0,0,2,0,0,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,1,2,2,1,3, 1,2,1,1,2,2,0,0,2,2,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,1,0,1,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,2,2,2,3,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,2,3,2,2,3,2,2,2,1,2,2,2,2, 1,2,1,1,2,2,0,1,2,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,0,2,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,0,2,2,2, 0,2,1,2,2,2,0,0,2,1,0,0,0,0,1,0,1,0,0,0,0,0,0,2,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,2,1,2,3,2,2,2, 1,2,1,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3,1,0,2,0,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,1,0,0,0,2,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,2,2,3,2,1,2,1,1,1, 0,1,1,1,1,1,3,0,1,0,0,0,0,2,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,0,1,0,0,0,0, 0,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,2,1,2,3,3,2,3,3,3,3,2,3,2,1,2,0,2,1,2, 0,2,0,2,2,2,0,0,1,2,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,1,2,2,3,3,2,3,2,3,2,2,3,1,2,2,0,2,2,2, 0,2,1,2,2,2,0,0,1,2,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,1,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,2,3,3,2,2,2,3,3,3,3,1,3,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,3,3,3,2,3,2,2,2,1,2,2,0,2,2,2,2, 0,2,0,2,2,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,1,3,2,3,3,2,3,3,2,2,1,2,2,2,2,2,2, 0,2,1,2,1,2,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,2,3,3,2,3,3,3,3,2,3,2,3,3,3,3,3,2,2,2,2,2,2,2,1, 0,2,0,1,2,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,3,3,3,2,1,2,3,3,3,3,3,3,3,2,3,2,3,2,1,2,3,0,2,1,2,2, 0,2,1,1,2,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,2,0, 3,3,3,3,3,3,3,3,3,2,3,3,3,3,2,1,3,1,2,2,2,1,2,3,3,1,2,1,2,2,2,2, 0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,2,0,0,0,0,0,0,0,0, 3,3,3,3,3,3,3,3,3,3,0,2,3,3,3,1,3,3,3,1,2,2,2,2,1,1,2,2,2,2,2,2, 0,2,0,1,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,3,3,3,3,3,2,3,3,3,2,2,3,3,3,2,1,2,3,2,3,2,2,2,2,1,2,1,1,1,2,2, 0,2,1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,1,0,0,0,0,0, 1,0,1,0,0,0,0,0,2,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,3,3,3,3,2,3,3,2,3,1,2,2,2,2,3,2,3,1,1,2,2,1,2,2,1,1,0,2,2,2,2, 0,1,0,1,2,2,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0, 3,0,0,1,1,0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,2,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,1,0,1,0,1,1,0,1,1,0,0,0,1,1,0,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 3,0,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0, 3,2,2,1,2,2,2,2,2,2,2,1,2,2,1,2,2,1,1,1,1,1,1,1,1,2,1,1,0,3,3,3, 0,3,0,2,2,2,2,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 2,2,2,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,2,1,2,2,2,1,1,1,2,0,1, 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,0,0,0,0, 2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,2,0,2,2,0,0,0,0,0,0, 0,0,0,1,1,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, 2,3,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,2,1,0,2,1,0, 0,0,0,0,1,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, 3,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,0,1,1,1,1,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,0,0,0,0,1,0,0,0,0,0,0,0,0,0, 0,3,1,1,2,2,2,2,2,1,2,2,2,1,1,2,2,2,2,2,2,2,1,2,2,1,0,1,1,1,1,0, 0,1,0,0,1,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, 3,2,1,1,1,1,2,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,2,0,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0,0,1,0,0, 2,1,1,2,2,2,2,2,2,2,2,2,2,2,1,2,2,2,2,2,1,2,1,2,1,1,1,1,0,0,0,0, 0,0,0,1,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, 1,2,1,2,2,2,2,2,2,2,2,2,2,1,2,1,2,1,1,2,1,1,1,2,1,2,1,2,0,1,0,1, 0,0,0,0,1,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,3,1,2,2,2,1,2,2,2,2,2,2,2,2,1,2,1,1,1,1,1,1,2,1,2,1,1,0,1,0,1, 0,0,0,0,1,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, 2,1,2,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2, 0,2,0,1,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0, 3,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,1,1,1,1,1,1,1,0,1,1,0,1,0,0,1,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,2,0,1,1,1,0,1,0,0,0,1,1,0,1,1,0,0,0,0,0,1,1,0,0, 0,1,1,1,2,1,2,2,2,0,2,0,2,0,1,1,2,1,1,1,1,2,1,0,1,1,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,0,0,0,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,1,0,0,0,0,0,1,0,1,2,2,0,1,0,0,1,1,2,2,1,2,0,2,0,0,0,1,2,0,1, 2,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,0,0,0, 0,0,0,0,0,0,0,0,2,0,2,1,2,0,2,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1, 2,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,0,0,0, 0,0,1,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,1,2,2,0,0,1,0,0,0,1,0,0,1, 1,1,2,1,0,1,1,1,0,1,0,1,1,1,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,2,2,1, 0,2,0,1,2,1,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, 2,1,0,0,1,0,1,1,1,1,0,0,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,2,1,0,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,0,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,1,0,1,0,0,1,0,0,0,0,0,1,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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,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,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,1,0,1,0,0,1,1,2,1,1,2,0,1,0,0,0,1,1,0,1, 1,0,0,1,0,0,1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,0,0,2,1,1,2,0,2,0,0,0,1,1,0,1, 1,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,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,2,2,1,2,1,1,0,1,0,0,0,1,1,0,1, 2,0,1,0,0,1,1,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,0,0,0,0,0,0,0,1,2,2,0,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,1,0,1, 1,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,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,2,0,0,0,0,2,1,1,1,0,2,1,1,0,0,0,2,1,0,1, 1,0,0,1,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, 0,0,0,0,0,0,0,0,1,0,1,1,2,0,1,0,0,1,1,0,2,1,1,0,1,0,0,0,1,1,0,1, 2,2,1,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 2,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,0,0,0, 0,0,0,0,0,0,0,0,1,0,2,1,1,0,1,0,0,1,1,0,1,2,1,0,2,0,0,0,1,1,0,1, 2,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,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,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,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,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, 0,1,0,0,2,0,2,1,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,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,0,0,0,0,0, 1,0,0,1,0,0,1,0,0,1,0,0,1,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,1,0,1,1,2,0,1,0,0,1,1,1,0,1,0,0,1,0,0,0,1,0,0,1, 1,0,0,1,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, 1,0,0,0,0,0,0,0,1,0,1,1,0,0,1,0,0,2,1,1,1,1,1,0,1,0,0,0,0,1,0,1, 0,1,1,1,2,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,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,0,0,0,0,0,0,0,0,0,0,0, 1,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,0,0,0, 0,0,0,0,0,0,0,0,0,0,1,2,1,0,0,0,0,0,1,1,1,1,1,0,1,0,0,0,1,1,0,0, }; public static readonly SequenceModel Win1255Model = new SequenceModel( win1255_CharToOrderMap, HebrewLangModel, 0.984004f, false, "windows-1255" ); } }
using Prism.Commands; using Prism.Mvvm; using Prism.Navigation; using Prism.Services; using Xamarin.Forms; using Reactive.Bindings; using Reactive.Bindings.Extensions; using System.Reactive.Linq; using System.Threading.Tasks; using System; namespace AiEffects.TestApp.ViewModels { public class AddCommandPageViewModel : BindableBase, IDestructible, INavigationAware { private bool _EnableSound; public bool EnableSound { get { return _EnableSound; } set { SetProperty(ref _EnableSound, value); } } private bool _EffectOn; public bool EffectOn { get { return _EffectOn; } set { SetProperty(ref _EffectOn, value); } } private Color _EffectColor; public Color EffectColor { get { return _EffectColor; } set { SetProperty(ref _EffectColor, value); } } private bool _IsExecutedCommand; public bool IsExecutedCommand { get { return _IsExecutedCommand; } set { SetProperty(ref _IsExecutedCommand, value); } } private string _CommandParameterText; public string CommandParameterText { get { return _CommandParameterText; } set { SetProperty(ref _CommandParameterText, value); } } private bool _IsExecutedLong; public bool IsExecutedLong { get { return _IsExecutedLong; } set { SetProperty(ref _IsExecutedLong, value); } } private bool _EnableRipple; public bool EnableRipple { get { return _EnableRipple; } set { SetProperty(ref _EnableRipple, value); } } private string _TestParam; public string TestParam { get { return _TestParam; } set { SetProperty(ref _TestParam, value); } } private string _TestLongParam; public string TestLongParam { get { return _TestLongParam; } set { SetProperty(ref _TestLongParam, value); } } private bool _SyncCanExecute; public bool SyncCanExecute { get { return _SyncCanExecute; } set { SetProperty(ref _SyncCanExecute, value); } } private DelegateCommand _ResetCommand; public DelegateCommand ResetCommand { get { return _ResetCommand = _ResetCommand ?? new DelegateCommand(() => { IsExecutedCommand = false; IsExecutedLong = false; CommandParameterText = ""; }); } } private DelegateCommand _ChangeEffectColorCommand; public DelegateCommand ChangeEffectColorCommand { get { return _ChangeEffectColorCommand = _ChangeEffectColorCommand ?? new DelegateCommand(() => { EffectColor = Color.FromHex("#FF00FF"); }); } } private DelegateCommand _ChangeParameterCommand; public DelegateCommand ChangeParameterCommand { get { return _ChangeParameterCommand = _ChangeParameterCommand ?? new DelegateCommand(() => { TestParam = "Fuga"; }); } } private DelegateCommand _ChangeLongParamCommand; public DelegateCommand ChangeLongParamCommand { get { return _ChangeLongParamCommand = _ChangeLongParamCommand ?? new DelegateCommand(() => { TestLongParam = "LongFuga"; }); } } private DelegateCommand _ChangeRippleCommand; public DelegateCommand ChangeRippleCommand { get { return _ChangeRippleCommand = _ChangeRippleCommand ?? new DelegateCommand(() => { EnableRipple = !EnableRipple; }); } } private DelegateCommand _ToggleEffectCommand; public DelegateCommand ToggleEffectCommand { get { return _ToggleEffectCommand = _ToggleEffectCommand ?? new DelegateCommand(() => { EffectOn = !EffectOn; }); } } public ReactiveCommand EffectCommand { get; set; } public ReactiveCommand LongCommand { get; set; } public ReactiveCommand ChangeCommand { get; set; } = new ReactiveCommand(); public ReactiveCommand ChangeLongCommand { get; set; } = new ReactiveCommand(); public ReactiveProperty<bool> CanExecute { get; } = new ReactiveProperty<bool>(true); public ReactiveProperty<bool> CanExecuteLong { get; } = new ReactiveProperty<bool>(false); public ReactiveCommand ToggleCanExecute { get; set; } = new ReactiveCommand(); public AsyncReactiveCommand CanExecuteCommand { get; set; } public ReactiveCommand CanExecuteLongCommand { get; set; } public ReactiveCommand CanExecuteNullToggle { get; set; } = new ReactiveCommand(); public ReactiveCommand CanExecuteLongNullToggle { get; set; } = new ReactiveCommand(); private INavigationService Navigation; public AddCommandPageViewModel(INavigationService navigationService) { Navigation = navigationService; EffectOn = true; EffectColor = Color.FromHex("#FFFF00"); IsExecutedCommand = false; IsExecutedLong = false; EnableRipple = true; TestParam = "Hoge"; TestLongParam = "LongHoge"; EnableSound = true; SyncCanExecute = true; ToggleCanExecute.Subscribe(_ => { CanExecute.Value = !CanExecute.Value; }); IDisposable subCommand = null; ChangeCommand.Subscribe(_ => { if (EffectCommand != null) { subCommand?.Dispose(); EffectCommand = null; } else { EffectCommand = CanExecute.ToReactiveCommand(); subCommand = EffectCommand.Subscribe(ExecCommand); } OnPropertyChanged(() => this.EffectCommand); }); ChangeCommand.Execute(); IDisposable subLongCommand = null; ChangeLongCommand.Subscribe(_ => { if (LongCommand != null) { subLongCommand.Dispose(); LongCommand = null; } else { LongCommand = CanExecute.ToReactiveCommand(); subLongCommand = LongCommand.Subscribe(ExecLongCommand); } OnPropertyChanged(() => this.LongCommand); }); ChangeLongCommand.Execute(); CanExecuteNullToggle.Subscribe(_ => { if (CanExecuteCommand != null) { CanExecuteCommand = null; CommandParameterText = "Command is null"; } else { CanExecuteCommand = CanExecute.ToAsyncReactiveCommand(); CanExecuteCommand.Subscribe(async x => { CommandParameterText = "Done Command"; await Task.Delay(500); }); } OnPropertyChanged(() => CanExecuteCommand); }); CanExecuteLongNullToggle.Subscribe(_ => { if (CanExecuteLongCommand != null) { CanExecuteLongCommand = null; CommandParameterText = "LongCommand is null"; } else { CanExecuteLongCommand = CanExecuteLong.ToReactiveCommand(); CanExecuteLongCommand.Subscribe(async x => { CommandParameterText = "Done Long Command"; await Task.Delay(500); }); } OnPropertyChanged(() => CanExecuteLongCommand); }); CanExecuteNullToggle.Execute(); CanExecuteLongNullToggle.Execute(); } void ExecCommand(object p) { IsExecutedCommand = true; CommandParameterText = p.ToString(); } void ExecLongCommand(object p) { IsExecutedLong = true; CommandParameterText = p.ToString(); } public void Destroy() { //EffectOn = false; } public void OnNavigatedFrom(NavigationParameters parameters) { } public void OnNavigatedTo(NavigationParameters parameters) { } public void OnNavigatingTo(NavigationParameters parameters) { } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Erik Ejlskov Jensen, http://erikej.blogspot.com/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: SqlServerCompactErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Data; using System.Data.SqlServerCe; using System.IO; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses SQL Server /// Compact 4 as its backing store. /// </summary> public class SqlServerCompactErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SqlServerCompactErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new Elmah.ApplicationException("Connection string is missing for the SQL Server Compact error log."); _connectionString = connectionString; InitializeDatabase(); ApplicationName = Mask.NullString((string) config["applicationName"]); } /// <summary> /// Initializes a new instance of the <see cref="SqlServerCompactErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SqlServerCompactErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString); InitializeDatabase(); } private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; using (SqlCeEngine engine = new SqlCeEngine(ConnectionString)) { engine.CreateDatabase(); } using (SqlCeConnection conn = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand cmd = new SqlCeCommand()) { conn.Open(); SqlCeTransaction transaction = conn.BeginTransaction(); try { cmd.Connection = conn; cmd.Transaction = transaction; cmd.CommandText = @" SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'ELMAH_Error'"; object obj = cmd.ExecuteScalar(); if (obj == null) { cmd.CommandText = @" CREATE TABLE ELMAH_Error ( [ErrorId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), [Application] NVARCHAR(60) NOT NULL, [Host] NVARCHAR(50) NOT NULL, [Type] NVARCHAR(100) NOT NULL, [Source] NVARCHAR(60) NOT NULL, [Message] NVARCHAR(500) NOT NULL, [User] NVARCHAR(50) NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [Sequence] INT IDENTITY (1, 1) NOT NULL, [AllXml] NTEXT NOT NULL )"; cmd.ExecuteNonQuery(); cmd.CommandText = @" CREATE NONCLUSTERED INDEX [IX_Error_App_Time_Seq] ON [ELMAH_Error] ( [Application] ASC, [TimeUtc] DESC, [Sequence] DESC )"; cmd.ExecuteNonQuery(); } transaction.Commit(CommitMode.Immediate); } catch (SqlCeException) { transaction.Rollback(); throw; } } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQL Server Compact Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); const string query = @" INSERT INTO ELMAH_Error ( [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc], [AllXml] ) VALUES ( @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml);"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(query, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = error.HostName; parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = error.Type; parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = error.Source; parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = error.Message; parameters.Add("@User", SqlDbType.NVarChar, 50).Value = error.User; parameters.Add("@StatusCode", SqlDbType.Int).Value = error.StatusCode; parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", SqlDbType.NText).Value = errorXml; command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); return id.ToString(); } } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> /// public override int GetErrors(int pageIndex, int pageSize, System.Collections.IList errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc] FROM [ELMAH_Error] ORDER BY [TimeUtc] DESC, [Sequence] DESC OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY; "; const string getCount = @" SELECT COUNT(*) FROM [ELMAH_Error]"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { connection.Open(); using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex; parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; using (SqlCeDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Elmah.Error error = new Elmah.Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } } } using (SqlCeCommand command = new SqlCeCommand(getCount, connection)) { return (int)command.ExecuteScalar(); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { command.Parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = errorGuid; connection.Open(); string errorXml = (string)command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } } #endif // !NET_1_1 && !NET_1_0
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using TestFirst.Net.Lang; using TestFirst.Net.Matcher.Internal; namespace TestFirst.Net.Matcher { /// <summary> /// Usage: /// <para> /// AList /// .InOrder() /// .WithOnly(AString.containing("x")) /// .And(AString.EqualTo("foo")) /// </para> /// </summary> public static class AList { // ReSharper enable PossibleMultipleEnumeration public interface IListMatcher<in T> : IMatcher<IEnumerable<T>>, IMatcher<IEnumerable>, IMatcher { } /// <summary> /// A list matcher which can have additional matchers added /// </summary> /// <typeparam name="T">The type being matched</typeparam> public interface IAcceptMoreMatchers<T> : IListMatcher<T> { IAcceptMoreMatchers<T> And(IMatcher<T> itemMatcher); } public static ListOfMatchBuilder<int> OfInts() { return Of<int>(); } public static ListOfMatchBuilder<DateTime> OfDateTimes() { return Of<DateTime>(); } public static ListOfMatchBuilder<DateTimeOffset> OfDateTimeOffsets() { return Of<DateTimeOffset>(); } public static ListOfMatchBuilder<Guid> OfGuids() { return Of<Guid>(); } public static ListOfMatchBuilder<float> OfFloats() { return Of<float>(); } public static ListOfMatchBuilder<long> OfLongs() { return new ListOfMatchBuilder<long>(); } public static ListOfMatchBuilder<char> OfChars() { return Of<char>(); } public static ListOfMatchBuilder<double> OfDoubles() { return Of<double>(); } public static ListOfMatchBuilder<string> OfStrings() { return Of<string>(); } public static ListOfMatchBuilder<object> OfObjects() { return Of<object>(); } public static ListOfMatchBuilder<T> Of<T>() { return new ListOfMatchBuilder<T>(); } /// <summary> /// Create a list of matchers, one for each of the given instances using the factory method provided. /// <para> /// E.g. /// </para> /// <para> /// AList.InAnyOrder().WithOnly(AList.From(AnInstance.EqualTo, items)) /// </para> /// </summary> /// <returns>A list of matchers, one per instance</returns> /// <param name="factory">The factory method which will create matchers for each instance in the list</param> /// <param name="instances">The list of items to create matchers from</param> /// <typeparam name="T">The type of element in the list</typeparam> public static IEnumerable<IMatcher<T>> From<T>(Func<T, IMatcher<T>> factory, IEnumerable<T> instances) { return instances.Select(factory.Invoke).ToList(); } /// <summary> /// A list with only one element. If you need more use InOrder()/InAnyOrder() ... /// </summary> /// <typeparam name="T">The type being matched</typeparam> /// <param name="matcher">The matcher</param> /// <returns>A list matcher</returns> public static IListMatcher<T> WithOnly<T>(IMatcher<T> matcher) { return InOrder().WithOnly(matcher); } public static IAcceptMoreMatchers<T> Without<T>(IMatcher<T> matcher) { return new AListNotContains<T>().And(matcher); } /// <summary> /// Return a matcher which allows matchers to match in any order. Currently as soon as a matcher is matched /// it is removed from trying to match the remaining items. The matchers are applied in the order they were added /// against each item in the list. As soon as a matcher matches a given item both the items and matcher are removed /// from further processing. The process then moves on to the next item in the list /// </summary> /// <returns>A builder for matching in any order</returns> public static InAnyOrderMatchBuilder InAnyOrder() { return new InAnyOrderMatchBuilder(); } /// <summary> /// Return a matcher which requires all matchers to match in order /// </summary> /// <returns>A builder for matching in order</returns> public static InOrderMatchBuilder InOrder() { return new InOrderMatchBuilder(); } public static IListMatcher<T> NoItems<T>() { return new IsEmptyMatcher<T>(); } public static IListMatcher<object> WithNumItems(int count) { return WithNumItems(AnInt.EqualTo(count)); } public static IListMatcher<object> WithNumItems(IMatcher<int?> matcher) { return new NumItemsMatcher<object>(matcher); } public class ListOfMatchBuilder<T> { /// <summary> /// A list with only one element. If you need more use InOrder()/InAnyOrder() ... /// </summary> /// <param name="matcher">The matcher</param> /// <returns>A list matcher</returns> public IListMatcher<T> WithOnly(IMatcher<T> matcher) { return InOrder().WithOnly(matcher); } public IAcceptMoreMatchers<T> Without(IMatcher<T> matcher) { return new AListNotContains<T>().And(matcher); } /// <summary> /// Return a matcher which allows matchers to match in any order. Currently as soon as a matcher is matched /// it is removed from trying to match the remaining items. The matchers are applied in the order they were added /// against each item in the list. As soon as a matcher matches a given item both the items and matcher are removed /// from further processing. The process then moves on to the next item in the list /// </summary> /// <returns>A builder for matching in any order</returns> public InAnyOrderMatchBuilder InAnyOrder() { return new InAnyOrderMatchBuilder(); } /// <summary> /// Return a matcher which requires all matchers to match in order /// </summary> /// <returns>A builder for matching in order</returns> public InOrderMatchBuilder InOrder() { return new InOrderMatchBuilder(); } public IListMatcher<T> NoItems() { return new IsEmptyMatcher<T>(); } public IListMatcher<T> WithNumItems(int count) { return WithNumItems(AnInt.EqualTo(count)); } public IListMatcher<T> WithNumItems(IMatcher<int?> matcher) { return new NumItemsMatcher<T>(matcher); } } /// <summary> /// For items matchers where item order is important /// </summary> // ReSharper disable PossibleMultipleEnumeration public class InOrderMatchBuilder { /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>Builder for continuing to create the matcher</returns> /// <typeparam name="T">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithOnly<T>(params IMatcher<T>[] itemMatchers) { return OfType<T>().WithOnly(itemMatchers); } [Obsolete("Use WithOnlyValues(...) instead")] public IAcceptMoreMatchers<int?> WithOnly(params int?[] values) { return OfType<int?>().WithOnlyValues(values); } [Obsolete("Use WithOnlyValues(...) instead")] public IAcceptMoreMatchers<string> WithOnly(params string[] values) { return OfType<string>().WithOnlyValues(values); } public IAcceptMoreMatchers<T> WithOnlyValues<T>(params T[] values) { return OfType<T>().WithOnlyValues(values); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="valueToMatchFunc">The factory function to create matchers</param> /// <param name="values">The list of vales</param> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type of the item being matched</typeparam> /// <typeparam name="TVal">The type of value being enumerated</typeparam> public IAcceptMoreMatchers<T> WithOnly<T, TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return OfType<T>().WithOnly(valueToMatchFunc, values); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithOnly<T>(IEnumerable<IMatcher<T>> itemMatchers) { return OfType<T>().WithOnly(itemMatchers); } public IAcceptMoreMatchers<T> WithAtLeastValues<T>(params T[] values) { return OfType<T>().WithAtLeastValues(values); } [Obsolete("Use WithAtLeastValues(...) instead")] public IAcceptMoreMatchers<string> WithAtLeast(params string[] values) { return OfType<string>().WithAtLeastValues(values); } [Obsolete("Use WithAtLeastValues(...) instead")] public IAcceptMoreMatchers<int?> WithAtLeast(params int?[] values) { return OfType<int?>().WithAtLeastValues(values); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">THe list of matchers</param> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithAtLeast<T>(params IMatcher<T>[] itemMatchers) { return OfType<T>().WithAtLeast(itemMatchers); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="valueToMatchFunc">Function to get matcher for a given value</param> /// <param name="values">The list of values</param> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type being matched</typeparam> /// <typeparam name="TVal">The type being enumerated</typeparam> public IAcceptMoreMatchers<T> WithAtLeast<T, TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return OfType<T>().WithAtLeast(valueToMatchFunc, values); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <typeparam name="T">The type being matched</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast<T>(IEnumerable<IMatcher<T>> itemMatchers) { return OfType<T>().WithAtLeast(itemMatchers); } private InOrderMatchBuilder<T> OfType<T>() { return new InOrderMatchBuilder<T>(); } } /// <summary> /// For items matchers where item order is important /// </summary> /// <typeparam name="T">The type being matched</typeparam> // ReSharper disable PossibleMultipleEnumeration public class InOrderMatchBuilder<T> { /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly(params IMatcher<T>[] itemMatchers) { return WithOnly((IEnumerable<IMatcher<T>>)itemMatchers); } public IAcceptMoreMatchers<T> WithOnlyValues(params T[] values) { return WithOnly(AList.From(val => AnInstance.EqualTo(val), values)); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// <para> /// Usage: /// </para> /// <para> /// AList.OfStrings().InOrder().WithOnly(x => AString.Containing("x"), listOfStrings); /// </para> /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <typeparam name="TVal">The type being enumerated</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly<TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return WithOnly(Matchers.MatchersFromValues(valueToMatchFunc, values)); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly(IEnumerable<IMatcher<T>> itemMatchers) { PreConditions.AssertNotNull(itemMatchers, "itemMatchers"); return new AListInOrderWithOnlyMatcher<T>(itemMatchers); } public IAcceptMoreMatchers<T> WithAtLeastValues(params T[] values) { return WithAtLeast(AList.From(val => AnInstance.EqualTo(val), values)); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast(params IMatcher<T>[] itemMatchers) { return WithAtLeast((IEnumerable<IMatcher<T>>)itemMatchers); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <typeparam name="TVal">The type being enumerated</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast<TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return WithAtLeast(Matchers.MatchersFromValues(valueToMatchFunc, values)); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast(IEnumerable<IMatcher<T>> itemMatchers) { PreConditions.AssertNotNull(itemMatchers, "itemMatchers"); return new AListInOrderAtLeast<T>(itemMatchers); } } public class InAnyOrderMatchBuilder { /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithOnly<T>() { return OfType<T>().WithOnly(); } [Obsolete("Use WithOnly(...) instead")] public IAcceptMoreMatchers<string> WithOnly(params string[] values) { return OfType<string>().WithOnlyValues(values); } [Obsolete("Use WithOnly(...) instead")] public IAcceptMoreMatchers<int?> WithOnly(params int?[] values) { return OfType<int?>().WithOnlyValues(values); } public IAcceptMoreMatchers<T> WithOnlyValues<T>(params T[] values) { return OfType<T>().WithOnlyValues(values); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> /// <typeparam name="T">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithOnly<T>(params IMatcher<T>[] itemMatchers) { return OfType<T>().WithOnly(itemMatchers); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <typeparam name="T">The type being matched</typeparam> /// <typeparam name="TVal">The type being enumerated</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly<T, TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return OfType<T>().WithOnly(valueToMatchFunc, values); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <typeparam name="T">The type being matched</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly<T>(IEnumerable<IMatcher<T>> itemMatchers) { return OfType<T>().WithOnly(itemMatchers); } [Obsolete("Use WithAtLeast(...) instead")] public IAcceptMoreMatchers<string> WithAtLeast(params string[] values) { return OfType<string>().WithAtLeastValues(values); } [Obsolete("Use WithAtLeast(...) instead")] public IAcceptMoreMatchers<int?> WithAtLeast(params int?[] values) { return OfType<int?>().WithAtLeastValues(values); } public IAcceptMoreMatchers<T> WithAtLeastValues<T>(params T[] values) { return OfType<T>().WithAtLeastValues(values); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <typeparam name="T">The type being matched</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast<T>(params IMatcher<T>[] itemMatchers) { return OfType<T>().WithAtLeast(itemMatchers); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <typeparam name="T">The type being matched</typeparam> /// <typeparam name="TVal">The type being enumerated</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast<T, TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return OfType<T>().WithAtLeast(valueToMatchFunc, values); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <typeparam name="T">The type being matched</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast<T>(IEnumerable<IMatcher<T>> itemMatchers) { return OfType<T>().WithAtLeast(itemMatchers); } private InAnyOrderMatchBuilder<T> OfType<T>() { return new InAnyOrderMatchBuilder<T>(); } } public class InAnyOrderMatchBuilder<T> { /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly() { return new AListInAnyOrderWithOnly<T>(); } public IAcceptMoreMatchers<T> WithOnlyValues(params T[] values) { return WithOnly(AList.From(val => AnInstance.EqualTo(val), values)); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly(params IMatcher<T>[] itemMatchers) { return WithOnly((IEnumerable<IMatcher<T>>)itemMatchers); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <typeparam name="TVal">The type being enumerated</typeparam> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly<TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return WithOnly(Matchers.MatchersFromValues(valueToMatchFunc, values)); } /// <summary> /// Return a matcher which requires all items to match /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithOnly(IEnumerable<IMatcher<T>> itemMatchers) { PreConditions.AssertNotNull(itemMatchers, "itemMatchers"); return new AListInAnyOrderWithOnly<T>(itemMatchers); } public IAcceptMoreMatchers<T> WithAtLeastValues(params T[] values) { return WithAtLeast(AList.From(val => AnInstance.EqualTo(val), values)); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast(params IMatcher<T>[] itemMatchers) { return WithAtLeast((IEnumerable<IMatcher<T>>)itemMatchers); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="valueToMatchFunc">The factory to create a matcher for each value</param> /// <param name="values">The list of values</param> /// <returns>The matcher builder</returns> /// <typeparam name="TVal">The type being matched</typeparam> public IAcceptMoreMatchers<T> WithAtLeast<TVal>(Func<TVal, IMatcher<T>> valueToMatchFunc, IEnumerable<TVal> values) { return WithAtLeast(Matchers.MatchersFromValues(valueToMatchFunc, values)); } /// <summary> /// Return a matcher which requires only that all matchers match once, so additional non matched items are allowed /// </summary> /// <param name="itemMatchers">The list of matchers</param> /// <returns>The matcher builder</returns> public IAcceptMoreMatchers<T> WithAtLeast(IEnumerable<IMatcher<T>> itemMatchers) { PreConditions.AssertNotNull(itemMatchers, "itemMatchers"); return new AListInAnyOrderWithAtLeast<T>(itemMatchers); } } internal abstract class AbstractListMatcher<T> : AbstractMatcher<IEnumerable<T>>, IListMatcher<T>, IProvidePrettyTypeName { private readonly string m_shortName; internal AbstractListMatcher(string shortName) { m_shortName = shortName; } public string GetPrettyTypeName() { return "AList." + m_shortName + "(IEnumerable<" + ProvidePrettyTypeName.GetPrettyTypeNameFor<T>() + ">)"; } public override bool Matches(IEnumerable<T> actual, IMatchDiagnostics diagnostics) { return Matches(actual as IEnumerable, diagnostics); } public abstract bool Matches(IEnumerable actual, IMatchDiagnostics diagnostics); internal static IList AsEfficientList(IEnumerable items) { if (items == null) { return null; } var list = items as IList; if (list != null) { return list; } list = new List<object>(15); foreach (var item in items) { list.Add(item); } return list; } protected override bool IsValidType(object actual) { Type itemType = GetItemType(actual); return itemType != null && typeof(T).IsAssignableFrom(itemType); } protected override IEnumerable<T> Wrap(object actual) { // Mono seems to have issue casting IList<T> to IEnumerable<Nullable<T>> when T is a value type Type itemType = GetItemType(actual); if (itemType.IsValueType) { return new ValueTypeEnumerableWrapper<T>((IEnumerable)actual); } return (IEnumerable<T>)actual; } private Type GetItemType(object someCollection) { var type = someCollection.GetType(); var ienum = type.GetInterface(typeof(IEnumerable<>).Name); return ienum != null ? ienum.GetGenericArguments()[0] : null; } } private class IsEmptyMatcher<T> : NumItemsMatcher<T> { public IsEmptyMatcher() : base(AnInt.EqualTo(0)) { } } private class NumItemsMatcher<T> : AbstractListMatcher<T> { private readonly IMatcher<int?> m_countMatcher; public NumItemsMatcher(IMatcher<int?> countMatcher) : base("NumItems") { m_countMatcher = countMatcher; } public override bool Matches(IEnumerable instance, IMatchDiagnostics diag) { var enummerator = instance.GetEnumerator(); int count = 0; while (enummerator.MoveNext()) { count++; } return diag.TryMatch(count, "count", m_countMatcher); } } private class ValueTypeEnumerableWrapper<T> : IEnumerable<T>, IEnumerable { private readonly IEnumerable actual; public ValueTypeEnumerableWrapper(IEnumerable actual) { this.actual = actual; } public IEnumerator<T> GetEnumerator() { return new ValueTypeEnumerator(actual.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public override string ToString() { return actual.ToString(); } internal class ValueTypeEnumerator : IEnumerator<T> { private readonly IEnumerator m_actual; public ValueTypeEnumerator(IEnumerator actual) { m_actual = actual; } object IEnumerator.Current { get { return Current; } } public T Current { get { return (T)m_actual.Current; } } public bool MoveNext() { return m_actual.MoveNext(); } public void Reset() { m_actual.Reset(); } public void Dispose() { var d = m_actual as IDisposable; if (d != null) { d.Dispose(); } } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/bigtable/admin/table/v1/bigtable_table_data.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Bigtable.Admin.Table.V1 { /// <summary>Holder for reflection information generated from google/bigtable/admin/table/v1/bigtable_table_data.proto</summary> public static partial class BigtableTableDataReflection { #region Descriptor /// <summary>File descriptor for google/bigtable/admin/table/v1/bigtable_table_data.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static BigtableTableDataReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cjhnb29nbGUvYmlndGFibGUvYWRtaW4vdGFibGUvdjEvYmlndGFibGVfdGFi", "bGVfZGF0YS5wcm90bxIeZ29vZ2xlLmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYx", "GiNnb29nbGUvbG9uZ3J1bm5pbmcvb3BlcmF0aW9ucy5wcm90bxoeZ29vZ2xl", "L3Byb3RvYnVmL2R1cmF0aW9uLnByb3RvIv0CCgVUYWJsZRIMCgRuYW1lGAEg", "ASgJEjgKEWN1cnJlbnRfb3BlcmF0aW9uGAIgASgLMh0uZ29vZ2xlLmxvbmdy", "dW5uaW5nLk9wZXJhdGlvbhJSCg9jb2x1bW5fZmFtaWxpZXMYAyADKAsyOS5n", "b29nbGUuYmlndGFibGUuYWRtaW4udGFibGUudjEuVGFibGUuQ29sdW1uRmFt", "aWxpZXNFbnRyeRJPCgtncmFudWxhcml0eRgEIAEoDjI6Lmdvb2dsZS5iaWd0", "YWJsZS5hZG1pbi50YWJsZS52MS5UYWJsZS5UaW1lc3RhbXBHcmFudWxhcml0", "eRpjChNDb2x1bW5GYW1pbGllc0VudHJ5EgsKA2tleRgBIAEoCRI7CgV2YWx1", "ZRgCIAEoCzIsLmdvb2dsZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MS5Db2x1", "bW5GYW1pbHk6AjgBIiIKFFRpbWVzdGFtcEdyYW51bGFyaXR5EgoKBk1JTExJ", "UxAAImwKDENvbHVtbkZhbWlseRIMCgRuYW1lGAEgASgJEhUKDWdjX2V4cHJl", "c3Npb24YAiABKAkSNwoHZ2NfcnVsZRgDIAEoCzImLmdvb2dsZS5iaWd0YWJs", "ZS5hZG1pbi50YWJsZS52MS5HY1J1bGUi7QIKBkdjUnVsZRIaChBtYXhfbnVt", "X3ZlcnNpb25zGAEgASgFSAASLAoHbWF4X2FnZRgCIAEoCzIZLmdvb2dsZS5w", "cm90b2J1Zi5EdXJhdGlvbkgAEksKDGludGVyc2VjdGlvbhgDIAEoCzIzLmdv", "b2dsZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MS5HY1J1bGUuSW50ZXJzZWN0", "aW9uSAASPQoFdW5pb24YBCABKAsyLC5nb29nbGUuYmlndGFibGUuYWRtaW4u", "dGFibGUudjEuR2NSdWxlLlVuaW9uSAAaRQoMSW50ZXJzZWN0aW9uEjUKBXJ1", "bGVzGAEgAygLMiYuZ29vZ2xlLmJpZ3RhYmxlLmFkbWluLnRhYmxlLnYxLkdj", "UnVsZRo+CgVVbmlvbhI1CgVydWxlcxgBIAMoCzImLmdvb2dsZS5iaWd0YWJs", "ZS5hZG1pbi50YWJsZS52MS5HY1J1bGVCBgoEcnVsZUKDAQoiY29tLmdvb2ds", "ZS5iaWd0YWJsZS5hZG1pbi50YWJsZS52MUIWQmlndGFibGVUYWJsZURhdGFQ", "cm90b1ABWkNnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlz", "L2JpZ3RhYmxlL2FkbWluL3RhYmxlL3YxO3RhYmxlYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.LongRunning.OperationsReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.Table), global::Google.Bigtable.Admin.Table.V1.Table.Parser, new[]{ "Name", "CurrentOperation", "ColumnFamilies", "Granularity" }, null, new[]{ typeof(global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity) }, new pbr::GeneratedClrTypeInfo[] { null, }), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.ColumnFamily), global::Google.Bigtable.Admin.Table.V1.ColumnFamily.Parser, new[]{ "Name", "GcExpression", "GcRule" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule), global::Google.Bigtable.Admin.Table.V1.GcRule.Parser, new[]{ "MaxNumVersions", "MaxAge", "Intersection", "Union" }, new[]{ "Rule" }, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection), global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection.Parser, new[]{ "Rules" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union), global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union.Parser, new[]{ "Rules" }, null, null, null)}) })); } #endregion } #region Messages /// <summary> /// A collection of user data indexed by row, column, and timestamp. /// Each table is served using the resources of its parent cluster. /// </summary> public sealed partial class Table : pb::IMessage<Table> { private static readonly pb::MessageParser<Table> _parser = new pb::MessageParser<Table>(() => new Table()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Table> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableDataReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Table() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Table(Table other) : this() { name_ = other.name_; CurrentOperation = other.currentOperation_ != null ? other.CurrentOperation.Clone() : null; columnFamilies_ = other.columnFamilies_.Clone(); granularity_ = other.granularity_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Table Clone() { return new Table(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// A unique identifier of the form /// &lt;cluster_name>/tables/[_a-zA-Z0-9][-_.a-zA-Z0-9]* /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "current_operation" field.</summary> public const int CurrentOperationFieldNumber = 2; private global::Google.LongRunning.Operation currentOperation_; /// <summary> /// If this Table is in the process of being created, the Operation used to /// track its progress. As long as this operation is present, the Table will /// not accept any Table Admin or Read/Write requests. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.LongRunning.Operation CurrentOperation { get { return currentOperation_; } set { currentOperation_ = value; } } /// <summary>Field number for the "column_families" field.</summary> public const int ColumnFamiliesFieldNumber = 3; private static readonly pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>.Codec _map_columnFamilies_codec = new pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForMessage(18, global::Google.Bigtable.Admin.Table.V1.ColumnFamily.Parser), 26); private readonly pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> columnFamilies_ = new pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily>(); /// <summary> /// The column families configured for this table, mapped by column family id. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, global::Google.Bigtable.Admin.Table.V1.ColumnFamily> ColumnFamilies { get { return columnFamilies_; } } /// <summary>Field number for the "granularity" field.</summary> public const int GranularityFieldNumber = 4; private global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity granularity_ = 0; /// <summary> /// The granularity (e.g. MILLIS, MICROS) at which timestamps are stored in /// this table. Timestamps not matching the granularity will be rejected. /// Cannot be changed once the table is created. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity Granularity { get { return granularity_; } set { granularity_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Table); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Table other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(CurrentOperation, other.CurrentOperation)) return false; if (!ColumnFamilies.Equals(other.ColumnFamilies)) return false; if (Granularity != other.Granularity) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (currentOperation_ != null) hash ^= CurrentOperation.GetHashCode(); hash ^= ColumnFamilies.GetHashCode(); if (Granularity != 0) hash ^= Granularity.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (currentOperation_ != null) { output.WriteRawTag(18); output.WriteMessage(CurrentOperation); } columnFamilies_.WriteTo(output, _map_columnFamilies_codec); if (Granularity != 0) { output.WriteRawTag(32); output.WriteEnum((int) Granularity); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (currentOperation_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(CurrentOperation); } size += columnFamilies_.CalculateSize(_map_columnFamilies_codec); if (Granularity != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Granularity); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Table other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.currentOperation_ != null) { if (currentOperation_ == null) { currentOperation_ = new global::Google.LongRunning.Operation(); } CurrentOperation.MergeFrom(other.CurrentOperation); } columnFamilies_.Add(other.columnFamilies_); if (other.Granularity != 0) { Granularity = other.Granularity; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (currentOperation_ == null) { currentOperation_ = new global::Google.LongRunning.Operation(); } input.ReadMessage(currentOperation_); break; } case 26: { columnFamilies_.AddEntriesFrom(input, _map_columnFamilies_codec); break; } case 32: { granularity_ = (global::Google.Bigtable.Admin.Table.V1.Table.Types.TimestampGranularity) input.ReadEnum(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Table message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public enum TimestampGranularity { [pbr::OriginalName("MILLIS")] Millis = 0, } } #endregion } /// <summary> /// A set of columns within a table which share a common configuration. /// </summary> public sealed partial class ColumnFamily : pb::IMessage<ColumnFamily> { private static readonly pb::MessageParser<ColumnFamily> _parser = new pb::MessageParser<ColumnFamily>(() => new ColumnFamily()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ColumnFamily> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableDataReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ColumnFamily() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ColumnFamily(ColumnFamily other) : this() { name_ = other.name_; gcExpression_ = other.gcExpression_; GcRule = other.gcRule_ != null ? other.GcRule.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ColumnFamily Clone() { return new ColumnFamily(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// A unique identifier of the form &lt;table_name>/columnFamilies/[-_.a-zA-Z0-9]+ /// The last segment is the same as the "name" field in /// google.bigtable.v1.Family. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "gc_expression" field.</summary> public const int GcExpressionFieldNumber = 2; private string gcExpression_ = ""; /// <summary> /// Garbage collection expression specified by the following grammar: /// GC = EXPR /// | "" ; /// EXPR = EXPR, "||", EXPR (* lowest precedence *) /// | EXPR, "&amp;&amp;", EXPR /// | "(", EXPR, ")" (* highest precedence *) /// | PROP ; /// PROP = "version() >", NUM32 /// | "age() >", NUM64, [ UNIT ] ; /// NUM32 = non-zero-digit { digit } ; (* # NUM32 &lt;= 2^32 - 1 *) /// NUM64 = non-zero-digit { digit } ; (* # NUM64 &lt;= 2^63 - 1 *) /// UNIT = "d" | "h" | "m" (* d=days, h=hours, m=minutes, else micros *) /// GC expressions can be up to 500 characters in length /// /// The different types of PROP are defined as follows: /// version() - cell index, counting from most recent and starting at 1 /// age() - age of the cell (current time minus cell timestamp) /// /// Example: "version() > 3 || (age() > 3d &amp;&amp; version() > 1)" /// drop cells beyond the most recent three, and drop cells older than three /// days unless they're the most recent cell in the row/column /// /// Garbage collection executes opportunistically in the background, and so /// it's possible for reads to return a cell even if it matches the active GC /// expression for its family. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string GcExpression { get { return gcExpression_; } set { gcExpression_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "gc_rule" field.</summary> public const int GcRuleFieldNumber = 3; private global::Google.Bigtable.Admin.Table.V1.GcRule gcRule_; /// <summary> /// Garbage collection rule specified as a protobuf. /// Supersedes `gc_expression`. /// Must serialize to at most 500 bytes. /// /// NOTE: Garbage collection executes opportunistically in the background, and /// so it's possible for reads to return a cell even if it matches the active /// GC expression for its family. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.Table.V1.GcRule GcRule { get { return gcRule_; } set { gcRule_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ColumnFamily); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ColumnFamily other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (GcExpression != other.GcExpression) return false; if (!object.Equals(GcRule, other.GcRule)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (GcExpression.Length != 0) hash ^= GcExpression.GetHashCode(); if (gcRule_ != null) hash ^= GcRule.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (GcExpression.Length != 0) { output.WriteRawTag(18); output.WriteString(GcExpression); } if (gcRule_ != null) { output.WriteRawTag(26); output.WriteMessage(GcRule); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (GcExpression.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(GcExpression); } if (gcRule_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GcRule); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ColumnFamily other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.GcExpression.Length != 0) { GcExpression = other.GcExpression; } if (other.gcRule_ != null) { if (gcRule_ == null) { gcRule_ = new global::Google.Bigtable.Admin.Table.V1.GcRule(); } GcRule.MergeFrom(other.GcRule); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { GcExpression = input.ReadString(); break; } case 26: { if (gcRule_ == null) { gcRule_ = new global::Google.Bigtable.Admin.Table.V1.GcRule(); } input.ReadMessage(gcRule_); break; } } } } } /// <summary> /// Rule for determining which cells to delete during garbage collection. /// </summary> public sealed partial class GcRule : pb::IMessage<GcRule> { private static readonly pb::MessageParser<GcRule> _parser = new pb::MessageParser<GcRule>(() => new GcRule()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GcRule> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.BigtableTableDataReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GcRule() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GcRule(GcRule other) : this() { switch (other.RuleCase) { case RuleOneofCase.MaxNumVersions: MaxNumVersions = other.MaxNumVersions; break; case RuleOneofCase.MaxAge: MaxAge = other.MaxAge.Clone(); break; case RuleOneofCase.Intersection: Intersection = other.Intersection.Clone(); break; case RuleOneofCase.Union: Union = other.Union.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GcRule Clone() { return new GcRule(this); } /// <summary>Field number for the "max_num_versions" field.</summary> public const int MaxNumVersionsFieldNumber = 1; /// <summary> /// Delete all cells in a column except the most recent N. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int MaxNumVersions { get { return ruleCase_ == RuleOneofCase.MaxNumVersions ? (int) rule_ : 0; } set { rule_ = value; ruleCase_ = RuleOneofCase.MaxNumVersions; } } /// <summary>Field number for the "max_age" field.</summary> public const int MaxAgeFieldNumber = 2; /// <summary> /// Delete cells in a column older than the given age. /// Values must be at least one millisecond, and will be truncated to /// microsecond granularity. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration MaxAge { get { return ruleCase_ == RuleOneofCase.MaxAge ? (global::Google.Protobuf.WellKnownTypes.Duration) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.MaxAge; } } /// <summary>Field number for the "intersection" field.</summary> public const int IntersectionFieldNumber = 3; /// <summary> /// Delete cells that would be deleted by every nested rule. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection Intersection { get { return ruleCase_ == RuleOneofCase.Intersection ? (global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.Intersection; } } /// <summary>Field number for the "union" field.</summary> public const int UnionFieldNumber = 4; /// <summary> /// Delete cells that would be deleted by any nested rule. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union Union { get { return ruleCase_ == RuleOneofCase.Union ? (global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union) rule_ : null; } set { rule_ = value; ruleCase_ = value == null ? RuleOneofCase.None : RuleOneofCase.Union; } } private object rule_; /// <summary>Enum of possible cases for the "rule" oneof.</summary> public enum RuleOneofCase { None = 0, MaxNumVersions = 1, MaxAge = 2, Intersection = 3, Union = 4, } private RuleOneofCase ruleCase_ = RuleOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RuleOneofCase RuleCase { get { return ruleCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearRule() { ruleCase_ = RuleOneofCase.None; rule_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GcRule); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GcRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (MaxNumVersions != other.MaxNumVersions) return false; if (!object.Equals(MaxAge, other.MaxAge)) return false; if (!object.Equals(Intersection, other.Intersection)) return false; if (!object.Equals(Union, other.Union)) return false; if (RuleCase != other.RuleCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ruleCase_ == RuleOneofCase.MaxNumVersions) hash ^= MaxNumVersions.GetHashCode(); if (ruleCase_ == RuleOneofCase.MaxAge) hash ^= MaxAge.GetHashCode(); if (ruleCase_ == RuleOneofCase.Intersection) hash ^= Intersection.GetHashCode(); if (ruleCase_ == RuleOneofCase.Union) hash ^= Union.GetHashCode(); hash ^= (int) ruleCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ruleCase_ == RuleOneofCase.MaxNumVersions) { output.WriteRawTag(8); output.WriteInt32(MaxNumVersions); } if (ruleCase_ == RuleOneofCase.MaxAge) { output.WriteRawTag(18); output.WriteMessage(MaxAge); } if (ruleCase_ == RuleOneofCase.Intersection) { output.WriteRawTag(26); output.WriteMessage(Intersection); } if (ruleCase_ == RuleOneofCase.Union) { output.WriteRawTag(34); output.WriteMessage(Union); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ruleCase_ == RuleOneofCase.MaxNumVersions) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(MaxNumVersions); } if (ruleCase_ == RuleOneofCase.MaxAge) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(MaxAge); } if (ruleCase_ == RuleOneofCase.Intersection) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Intersection); } if (ruleCase_ == RuleOneofCase.Union) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Union); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GcRule other) { if (other == null) { return; } switch (other.RuleCase) { case RuleOneofCase.MaxNumVersions: MaxNumVersions = other.MaxNumVersions; break; case RuleOneofCase.MaxAge: MaxAge = other.MaxAge; break; case RuleOneofCase.Intersection: Intersection = other.Intersection; break; case RuleOneofCase.Union: Union = other.Union; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { MaxNumVersions = input.ReadInt32(); break; } case 18: { global::Google.Protobuf.WellKnownTypes.Duration subBuilder = new global::Google.Protobuf.WellKnownTypes.Duration(); if (ruleCase_ == RuleOneofCase.MaxAge) { subBuilder.MergeFrom(MaxAge); } input.ReadMessage(subBuilder); MaxAge = subBuilder; break; } case 26: { global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection subBuilder = new global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Intersection(); if (ruleCase_ == RuleOneofCase.Intersection) { subBuilder.MergeFrom(Intersection); } input.ReadMessage(subBuilder); Intersection = subBuilder; break; } case 34: { global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union subBuilder = new global::Google.Bigtable.Admin.Table.V1.GcRule.Types.Union(); if (ruleCase_ == RuleOneofCase.Union) { subBuilder.MergeFrom(Union); } input.ReadMessage(subBuilder); Union = subBuilder; break; } } } } #region Nested types /// <summary>Container for nested types declared in the GcRule message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// A GcRule which deletes cells matching all of the given rules. /// </summary> public sealed partial class Intersection : pb::IMessage<Intersection> { private static readonly pb::MessageParser<Intersection> _parser = new pb::MessageParser<Intersection>(() => new Intersection()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Intersection> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.GcRule.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Intersection() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Intersection(Intersection other) : this() { rules_ = other.rules_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Intersection Clone() { return new Intersection(this); } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Bigtable.Admin.Table.V1.GcRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Bigtable.Admin.Table.V1.GcRule.Parser); private readonly pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> rules_ = new pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule>(); /// <summary> /// Only delete cells which would be deleted by every element of `rules`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> Rules { get { return rules_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Intersection); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Intersection other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Intersection other) { if (other == null) { return; } rules_.Add(other.rules_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } /// <summary> /// A GcRule which deletes cells matching any of the given rules. /// </summary> public sealed partial class Union : pb::IMessage<Union> { private static readonly pb::MessageParser<Union> _parser = new pb::MessageParser<Union>(() => new Union()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Union> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Bigtable.Admin.Table.V1.GcRule.Descriptor.NestedTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Union() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Union(Union other) : this() { rules_ = other.rules_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Union Clone() { return new Union(this); } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Bigtable.Admin.Table.V1.GcRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Bigtable.Admin.Table.V1.GcRule.Parser); private readonly pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> rules_ = new pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule>(); /// <summary> /// Delete cells which would be deleted by any element of `rules`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Bigtable.Admin.Table.V1.GcRule> Rules { get { return rules_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Union); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Union other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rules_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { rules_.WriteTo(output, _repeated_rules_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Union other) { if (other == null) { return; } rules_.Add(other.rules_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } } #endregion } #endregion } #endregion Designer generated code
using System.Drawing; using pol = Anycmd.Xacml.Policy; namespace Anycmd.Xacml.ControlCenter.CustomControls { /// <summary> /// Summary description for PolicySet. /// </summary> public class Policy : BaseControl { private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtDescription; private System.Windows.Forms.GroupBox grpDefaults; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox txtXPathVersion; private System.Windows.Forms.TextBox txtPolicyId; private System.Windows.Forms.ComboBox cmbRuleCombiningAlgorithm; private pol.PolicyElementReadWrite _policy; private System.Windows.Forms.Button btnApply; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// /// </summary> public Policy( pol.PolicyElementReadWrite policy ) { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); LoadingData = true; _policy = policy; cmbRuleCombiningAlgorithm.Items.Add( Consts.Schema1.RuleCombiningAlgorithms.DenyOverrides ); cmbRuleCombiningAlgorithm.Items.Add( Consts.Schema1.RuleCombiningAlgorithms.PermitOverrides ); cmbRuleCombiningAlgorithm.Items.Add( Consts.Schema1.RuleCombiningAlgorithms.FirstApplicable ); txtDescription.Text = _policy.Description; txtPolicyId.Text = _policy.Id; txtXPathVersion.Text = _policy.XPathVersion; cmbRuleCombiningAlgorithm.SelectedText = _policy.RuleCombiningAlgorithm; txtDescription.DataBindings.Add( "Text", _policy, "Description" ); txtPolicyId.DataBindings.Add( "Text", _policy, "Id" ); if(_policy.XPathVersion != null) txtXPathVersion.DataBindings.Add( "Text", _policy, "XPathVersion" ); cmbRuleCombiningAlgorithm.DataBindings.Add( "SelectedValue", policy, "RuleCombiningAlgorithm" ); LoadingData = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.txtDescription = new System.Windows.Forms.TextBox(); this.grpDefaults = new System.Windows.Forms.GroupBox(); this.txtXPathVersion = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txtPolicyId = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.cmbRuleCombiningAlgorithm = new System.Windows.Forms.ComboBox(); this.btnApply = new System.Windows.Forms.Button(); this.grpDefaults.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.TabIndex = 0; this.label1.Text = "Description:"; // // txtDescription // this.txtDescription.Location = new System.Drawing.Point(80, 8); this.txtDescription.Multiline = true; this.txtDescription.Name = "txtDescription"; this.txtDescription.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtDescription.Size = new System.Drawing.Size(504, 64); this.txtDescription.TabIndex = 1; this.txtDescription.Text = ""; this.txtDescription.TextChanged += TextBox_TextChanged; // // grpDefaults // this.grpDefaults.Controls.Add(this.txtXPathVersion); this.grpDefaults.Controls.Add(this.label4); this.grpDefaults.Location = new System.Drawing.Point(8, 144); this.grpDefaults.Name = "grpDefaults"; this.grpDefaults.Size = new System.Drawing.Size(576, 56); this.grpDefaults.TabIndex = 2; this.grpDefaults.TabStop = false; this.grpDefaults.Text = "Policy Defaults"; // // txtXPathVersion // this.txtXPathVersion.Location = new System.Drawing.Point(88, 24); this.txtXPathVersion.Name = "txtXPathVersion"; this.txtXPathVersion.Size = new System.Drawing.Size(480, 20); this.txtXPathVersion.TabIndex = 1; this.txtXPathVersion.Text = ""; this.txtXPathVersion.TextChanged += TextBox_TextChanged; // // label4 // this.label4.Location = new System.Drawing.Point(8, 24); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(176, 23); this.label4.TabIndex = 0; this.label4.Text = "XPath version:"; // // label2 // this.label2.Location = new System.Drawing.Point(8, 80); this.label2.Name = "label2"; this.label2.TabIndex = 0; this.label2.Text = "Policy Id:"; // // txtPolicyId // this.txtPolicyId.Location = new System.Drawing.Point(80, 80); this.txtPolicyId.Name = "txtPolicyId"; this.txtPolicyId.Size = new System.Drawing.Size(504, 20); this.txtPolicyId.TabIndex = 1; this.txtPolicyId.Text = ""; this.txtPolicyId.TextChanged += TextBox_TextChanged; // // label3 // this.label3.Location = new System.Drawing.Point(8, 112); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(176, 23); this.label3.TabIndex = 0; this.label3.Text = "Rule Combining Algorithm:"; // // cmbRuleCombiningAlgorithm // this.cmbRuleCombiningAlgorithm.Location = new System.Drawing.Point(152, 112); this.cmbRuleCombiningAlgorithm.Name = "cmbRuleCombiningAlgorithm"; this.cmbRuleCombiningAlgorithm.Size = new System.Drawing.Size(432, 21); this.cmbRuleCombiningAlgorithm.TabIndex = 3; this.cmbRuleCombiningAlgorithm.SelectedIndexChanged += ComboBox_SelectedIndexChanged; // // button1 // this.btnApply.Location = new System.Drawing.Point(264, 208); this.btnApply.Name = "btnApply"; this.btnApply.TabIndex = 4; this.btnApply.Text = "Apply"; this.btnApply.Click += new System.EventHandler(this.button1_Click); // // Policy // this.Controls.Add(this.btnApply); this.Controls.Add(this.cmbRuleCombiningAlgorithm); this.Controls.Add(this.grpDefaults); this.Controls.Add(this.txtDescription); this.Controls.Add(this.label1); this.Controls.Add(this.txtPolicyId); this.Controls.Add(this.label2); this.Controls.Add(this.label3); this.Name = "Policy"; this.Size = new System.Drawing.Size(592, 232); this.grpDefaults.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void button1_Click(object sender, System.EventArgs e) { _policy.Description = txtDescription.Text; _policy.Id = txtPolicyId.Text; _policy.XPathVersion = txtXPathVersion.Text; _policy.RuleCombiningAlgorithm = cmbRuleCombiningAlgorithm.SelectedText; ModifiedValue = false; txtDescription.BackColor = Color.White; txtPolicyId.BackColor = Color.White; txtXPathVersion.BackColor = Color.White; cmbRuleCombiningAlgorithm.BackColor = Color.White; } /// <summary> /// /// </summary> public pol.PolicyElementReadWrite PolicyElement { get{ return _policy; } } } }
using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; namespace Rainbow.Framework.Web.UI.WebControls { /// <summary> /// Paging class, Rainbow special edition /// </summary> [ DefaultProperty("PageNumber"), ToolboxData("<{0}:Paging TextKey='' runat=server></{0}:Paging>"), Designer("Rainbow.Framework.UI.Design.PagingDesigner") ] public class Paging : WebControl, IPaging { /// <summary> /// Page number /// </summary> protected TextBox tbPageNumber; /// <summary> /// Total page count /// </summary> protected Label lblPageCount; /// <summary> /// Label containg text 'of' /// </summary> protected Label lblof; /// <summary> /// Button 'First' /// </summary> protected Button btnFirst; /// <summary> /// Button 'Previous' /// </summary> protected Button btnPrev; /// <summary> /// Button 'Next' /// </summary> protected Button btnNext; /// <summary> /// Button 'Last' /// </summary> protected Button btnLast; /// <summary> /// Move event raised when a move is performed /// </summary> public event EventHandler OnMove; // variables we use to manage state private int m_recordsPerPage = 10; /// <summary> /// Number of records per page /// </summary> /// <value>The records per page.</value> public int RecordsPerPage { get { return m_recordsPerPage; } set { m_recordsPerPage = value; } } /// <summary> /// Hide when on single page hides controls when /// there is only one page /// </summary> /// <value><c>true</c> if [hide on single page]; otherwise, <c>false</c>.</value> public bool HideOnSinglePage { get { return Convert.ToBoolean(ViewState["HideOnSinglePage"]); } set { ViewState["HideOnSinglePage"] = value.ToString(); } } /// <summary> /// Current page number /// </summary> /// <value>The page number.</value> public int PageNumber { get { return Convert.ToInt32(tbPageNumber.Text); } set { tbPageNumber.Text = value.ToString(); } } /// <summary> /// Gets or sets a value indicating whether validation is performed when the control buttons are clicked. /// </summary> /// <value><c>true</c> if [causes validation]; otherwise, <c>false</c>.</value> [ Description( "Gets or sets a value indicating whether validation is performed when the control buttons are clicked.") ] public bool CausesValidation { get { object causesValidation = ViewState["CausesValidation"]; if (causesValidation != null) return (bool) causesValidation; else return true; } set { ViewState["CausesValidation"] = value; } } /// <summary> /// Total Record Count /// </summary> /// <value>The record count.</value> public int RecordCount { get { return Convert.ToInt32(ViewState["RecordCount"]); } set { ViewState["RecordCount"] = value.ToString(); } } /// <summary> /// Total pages count /// </summary> /// <value>The page count.</value> public int PageCount { get { // Calculate page count int _PageCount = RecordCount/RecordsPerPage; // adjust for spillover if (RecordCount%RecordsPerPage > 0) _PageCount++; if (_PageCount < 1) _PageCount = 1; return _PageCount; } } /// <summary> /// Used by OnMove event /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void OnMoveHandler(EventArgs e) { if (OnMove != null) { OnMove(this, e); } } /// <summary> /// Enable/disable the nav controls based on the current context, update labels /// </summary> public void RefreshButtons() { // enable/disable the nav controls based on the current context // we should only show the first button if we're NOT on the first page already btnFirst.Enabled = (PageNumber != 1); btnPrev.Enabled = (PageNumber > 1); btnNext.Enabled = (PageNumber < PageCount); btnLast.Enabled = (PageNumber != PageCount); //Update labels lblPageCount.Text = PageCount.ToString(); if (PageCount <= 1 && HideOnSinglePage) { btnFirst.Visible = false; btnPrev.Visible = false; btnNext.Visible = false; btnLast.Visible = false; lblof.Visible = false; lblPageCount.Visible = false; tbPageNumber.Visible = false; } else { btnFirst.Visible = true; btnPrev.Visible = true; btnNext.Visible = true; btnLast.Visible = true; lblof.Visible = true; lblPageCount.Visible = true; tbPageNumber.Visible = true; } } /// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { RefreshButtons(); } /// <summary> /// Main class manging pages /// </summary> public Paging() { //Construct controls btnFirst = new Button(); btnFirst.Width = new Unit("25px"); btnFirst.Font.Bold = true; btnFirst.Text = " |< "; btnFirst.CommandArgument = "first"; btnFirst.EnableViewState = false; Controls.Add(btnFirst); btnPrev = new Button(); btnPrev.Width = new Unit("25px"); btnPrev.Font.Bold = true; btnPrev.Text = " < "; btnPrev.CommandArgument = "prev"; btnPrev.EnableViewState = false; Controls.Add(btnPrev); Controls.Add(new LiteralControl("&#160;")); tbPageNumber = new TextBox(); tbPageNumber.Width = new Unit("30px"); tbPageNumber.EnableViewState = true; tbPageNumber.AutoPostBack = true; Controls.Add(tbPageNumber); Controls.Add(new LiteralControl("&#160;")); btnNext = new Button(); btnNext.Width = new Unit("25px"); btnNext.Font.Bold = true; btnNext.Text = " > "; btnNext.CommandArgument = "next"; btnNext.EnableViewState = false; Controls.Add(btnNext); btnLast = new Button(); btnLast.Width = new Unit("25px"); btnLast.Font.Bold = true; btnLast.Text = " >| "; btnLast.CommandArgument = "last"; btnLast.EnableViewState = false; Controls.Add(btnLast); lblof = new Label(); lblof.EnableViewState = false; lblof.Text = "&#160;/&#160;"; Controls.Add(lblof); lblPageCount = new Label(); lblPageCount.EnableViewState = false; Controls.Add(lblPageCount); //Set defaults if (ViewState["PageNumber"] == null) PageNumber = 1; if (ViewState["RecordCount"] == null) RecordCount = 1; if (ViewState["HideOnSinglePage"] == null) HideOnSinglePage = true; //Add handlers Load += new EventHandler(Page_Load); tbPageNumber.TextChanged += new EventHandler(NavigationTbClick); btnFirst.Click += new EventHandler(NavigationButtonClick); btnPrev.Click += new EventHandler(NavigationButtonClick); btnNext.Click += new EventHandler(NavigationButtonClick); btnLast.Click += new EventHandler(NavigationButtonClick); } /// <summary> /// Navigations the button click. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void NavigationButtonClick(Object sender, EventArgs e) { // get the command string arg = ((Button) sender).CommandArgument; // do the command switch (arg) { case ("next"): if (PageNumber < PageCount) PageNumber++; break; case ("prev"): if (PageNumber > 1) PageNumber--; break; case ("last"): PageNumber = PageCount; break; case ("first"): PageNumber = 1; break; } RefreshButtons(); //Raise the event OnMove OnMoveHandler(new EventArgs()); } /// <summary> /// Navigations the tb click. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void NavigationTbClick(Object sender, EventArgs e) { int _PageNumber = Convert.ToInt32(tbPageNumber.Text); if (_PageNumber > PageCount) { PageNumber = PageCount; } else if (_PageNumber < 1) { PageNumber = 1; } else { PageNumber = _PageNumber; } RefreshButtons(); //Raise the event OnMove OnMoveHandler(new EventArgs()); } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; /// <summary> /// Represents the response to a item search operation. /// </summary> /// <typeparam name="TItem">The type of items that the opeartion returned.</typeparam> internal sealed class FindItemResponse<TItem> : ServiceResponse where TItem : Item { private FindItemsResults<TItem> results; private bool isGrouped; private GroupedFindItemsResults<TItem> groupedFindResults; private PropertySet propertySet; /// <summary> /// Initializes a new instance of the <see cref="FindItemResponse&lt;TItem&gt;"/> class. /// </summary> /// <param name="isGrouped">if set to <c>true</c> if grouped.</param> /// <param name="propertySet">The property set.</param> internal FindItemResponse(bool isGrouped, PropertySet propertySet) : base() { this.isGrouped = isGrouped; this.propertySet = propertySet; EwsUtilities.Assert( this.propertySet != null, "FindItemResponse.ctor", "PropertySet should not be null"); } /// <summary> /// Reads response elements from XML. /// </summary> /// <param name="reader">The reader.</param> internal override void ReadElementsFromXml(EwsServiceXmlReader reader) { reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.RootFolder); int totalItemsInView = reader.ReadAttributeValue<int>(XmlAttributeNames.TotalItemsInView); bool moreItemsAvailable = !reader.ReadAttributeValue<bool>(XmlAttributeNames.IncludesLastItemInRange); // Ignore IndexedPagingOffset attribute if moreItemsAvailable is false. int? nextPageOffset = moreItemsAvailable ? reader.ReadNullableAttributeValue<int>(XmlAttributeNames.IndexedPagingOffset) : null; if (!this.isGrouped) { this.results = new FindItemsResults<TItem>(); this.results.TotalCount = totalItemsInView; this.results.NextPageOffset = nextPageOffset; this.results.MoreAvailable = moreItemsAvailable; InternalReadItemsFromXml( reader, this.propertySet, this.results.Items); } else { this.groupedFindResults = new GroupedFindItemsResults<TItem>(); this.groupedFindResults.TotalCount = totalItemsInView; this.groupedFindResults.NextPageOffset = nextPageOffset; this.groupedFindResults.MoreAvailable = moreItemsAvailable; reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Groups); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.IsStartElement(XmlNamespace.Types, XmlElementNames.GroupedItems)) { string groupIndex = reader.ReadElementValue(XmlNamespace.Types, XmlElementNames.GroupIndex); List<TItem> itemList = new List<TItem>(); InternalReadItemsFromXml( reader, this.propertySet, itemList); reader.ReadEndElement(XmlNamespace.Types, XmlElementNames.GroupedItems); this.groupedFindResults.ItemGroups.Add(new ItemGroup<TItem>(groupIndex, itemList)); } } while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Groups)); } } reader.ReadEndElement(XmlNamespace.Messages, XmlElementNames.RootFolder); reader.Read(); if (reader.IsStartElement(XmlNamespace.Messages, XmlElementNames.HighlightTerms) && !reader.IsEmptyElement) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { HighlightTerm term = new HighlightTerm(); term.LoadFromXml( reader, XmlNamespace.Types, XmlElementNames.HighlightTerm); this.results.HighlightTerms.Add(term); } } while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.HighlightTerms)); } } /// <summary> /// Read items from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="propertySet">The property set.</param> /// <param name="destinationList">The list in which to add the read items.</param> private static void InternalReadItemsFromXml( EwsServiceXmlReader reader, PropertySet propertySet, IList<TItem> destinationList) { EwsUtilities.Assert( destinationList != null, "FindItemResponse.InternalReadItemsFromXml", "destinationList is null."); reader.ReadStartElement(XmlNamespace.Types, XmlElementNames.Items); if (!reader.IsEmptyElement) { do { reader.Read(); if (reader.NodeType == XmlNodeType.Element) { TItem item = EwsUtilities.CreateEwsObjectFromXmlElementName<TItem>(reader.Service, reader.LocalName); if (item == null) { reader.SkipCurrentElement(); } else { item.LoadFromXml( reader, true, /* clearPropertyBag */ propertySet, true /* summaryPropertiesOnly */); destinationList.Add(item); } } } while (!reader.IsEndElement(XmlNamespace.Types, XmlElementNames.Items)); } } /// <summary> /// Creates an item instance. /// </summary> /// <param name="service">The service.</param> /// <param name="xmlElementName">Name of the XML element.</param> /// <returns>Item</returns> private TItem CreateItemInstance(ExchangeService service, string xmlElementName) { return EwsUtilities.CreateEwsObjectFromXmlElementName<TItem>(service, xmlElementName); } /// <summary> /// Gets a grouped list of items matching the specified search criteria that were found in Exchange. ItemGroups is /// null if the search operation did not specify grouping options. /// </summary> public GroupedFindItemsResults<TItem> GroupedFindResults { get { return this.groupedFindResults; } } /// <summary> /// Gets the results of the search operation. /// </summary> public FindItemsResults<TItem> Results { get { return this.results; } } } }
// 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 OrUInt32() { var test = new SimpleBinaryOpTest__OrUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local 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 SimpleBinaryOpTest__OrUInt32 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(UInt32); private const int Op2ElementCount = VectorSize / sizeof(UInt32); private const int RetElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector256<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector256<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static SimpleBinaryOpTest__OrUInt32() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<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<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__OrUInt32() { 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<Vector256<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<Vector256<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 SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Or( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Or( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Or( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Or), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrUInt32(); var result = Avx2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; 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); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if ((uint)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((uint)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Or)}<UInt32>(Vector256<UInt32>, Vector256<UInt32>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Printing; using System.IO; using System.Text; using System.Windows.Forms; using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using LythumOSL.Core; using LythumOSL.UI; using LythumOSL.Reporting.CR.Metadata; namespace LythumOSL.Reporting.CR { public partial class FrmReports : Form { #region Nested export type class public class ReportExportFormat { public ExportFormatType Type; public string Name; public string Ext; public ReportExportFormat ( ExportFormatType type, string name, string ext) { Type = type; Name = name; Ext = ext; } public override string ToString () { return Name; } } #endregion List<IReportCR> _Reports; int _Copies; IReportCR _LastReport = null; public FrmReports ( string name, List<IReportCR> reports, int copies) { InitializeComponent (); Text = name; Validation.RequireValid (reports, "reports"); _Reports = reports; _Copies = copies; TxtCopiesCount.Text = _Copies.ToString (); Init (); InitExport (); } void Init () { foreach (IReportCR r in _Reports) { LbxReports.Items.Add (r); //ListViewItem i = new ListViewItem (r.Name); //i.Tag = r; //LvwList.Items.Add (i); ////CmbPrinter.Text = r.Report.PrintOptions.PrinterName; //if (first == null) //{ // first = i; //} } if (LbxReports.Items.Count > 0) { LbxReports.SelectedIndex = 0; } //if (first != null) //{ // first.Selected = true; //} } void InitExport () { CmbExportFormat.Items.Clear (); CmbExportFormat.Items.Add (new ReportExportFormat ( ExportFormatType.WordForWindows, Properties.Resources.FrmReport_ExportFormat_DOC, "doc")); CmbExportFormat.Items.Add (new ReportExportFormat ( ExportFormatType.Excel, Properties.Resources.FrmReport_ExportFormat_Excel, "xls")); CmbExportFormat.Items.Add (new ReportExportFormat ( ExportFormatType.PortableDocFormat, Properties.Resources.FrmReport_ExportFormat_PDF, "pdf")); CmbExportFormat.Items.Add (new ReportExportFormat ( ExportFormatType.HTML40, Properties.Resources.FrmReport_ExportFormat_HTML, "html")); CmbExportFormat.Items.Add (new ReportExportFormat ( ExportFormatType.RichText, Properties.Resources.FrmReport_ExportFormat_RTF, "rtf")); if (CmbExportFormat.Items.Count > 0) { CmbExportFormat.SelectedIndex = 0; } } void Print (ReportDocument rpt) { //rpt.PrintOptions.PrinterName = CmbPrinter.Text; rpt.PrintToPrinter (_Copies, false, 0, 0); } private void LvwList_SelectedIndexChanged (object sender, EventArgs e) { //if (LvwList.SelectedItems.Count > 0) if (LbxReports.SelectedItems.Count > 0) { if (_LastReport != null) { _LastReport.DestroyReport (); } //_LastReport = (IReportCR)LvwList.SelectedItems[0].Tag; _LastReport = LbxReports.SelectedItem as IReportCR; CrvMain.ReportSource = _LastReport.GetReport (); //CrvMain.Refresh (); CrvMain.Enabled = CmdPrintAll.Enabled = CmdPrintOne.Enabled = true; } else { CrvMain.Enabled = CmdPrintAll.Enabled = CmdPrintOne.Enabled = false; } } private void CmdPrintOne_Click (object sender, EventArgs e) { //foreach (ListViewItem i in LvwList.SelectedItems) foreach (object o in LbxReports.SelectedItems) { IReportCR rpt = o as IReportCR; Print (rpt.GetReport ()); rpt.DestroyReport (); } } private void CmdPrintAll_Click (object sender, EventArgs e) { foreach (object o in LbxReports.SelectedItems) { IReportCR rpt = o as IReportCR; Print (rpt.GetReport()); rpt.DestroyReport (); } } private void FrmReports_Load (object sender, EventArgs e) { /* // Enum installed printers foreach (string printer in PrinterSettings.InstalledPrinters) { CmbPrinter.Items.Add (printer); } */ } private void FrmReports_Resize (object sender, EventArgs e) { //if(LbxReports.Columns.Count>0){ // LbxReports.Columns[0].Width = LvwList.Width - 10; //} } private void TxtCopiesCount_TextChanged (object sender, EventArgs e) { int copies = _Copies; try { _Copies = int.Parse (TxtCopiesCount.Text); } catch { _Copies = copies; } } #region EXPORT private void CmdExport_Click (object sender, EventArgs e) { try { this.Enabled = false; ExportFormatType exportFormat = ((ReportExportFormat)CmbExportFormat.SelectedItem).Type; string exportPath = "c:\\"; string exportExt = "." + ((ReportExportFormat)CmbExportFormat.SelectedItem).Ext; FolderBrowserDialog d = new FolderBrowserDialog (); d.ShowNewFolderButton = true; d.Description = Properties.Resources.FrmReport_ExportFolderTitle; d.RootFolder = Environment.SpecialFolder.MyComputer; if (d.ShowDialog () == DialogResult.OK) { if (Directory.Exists (d.SelectedPath)) { exportPath = d.SelectedPath; } } else { return; } if (LbxReports.SelectedItems.Count > 0) { foreach (object o in LbxReports.SelectedItems) { IReportCR rpt = o as IReportCR; ReportDocument rep = rpt.GetReport (); rep.ExportToDisk ( exportFormat, exportPath + "\\" + LythumOSL.Core.IO.File.FixFileName (rpt.Name) .Replace ('\\', '-') .Replace ('/', '-') + exportExt); } Messages.Warning ( Properties.Resources.FrmReport_ExportFinished); } } catch (Exception ex) { Messages.Error (ex.Message, Text); } finally { this.Enabled = true; } } #endregion private void TxtCopiesCount_Validating (object sender, CancelEventArgs e) { int result; e.Cancel = int.TryParse (TxtCopiesCount.Text, out result); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Mocument.Model; using Newtonsoft.Json; using Salient.HTTPArchiveModel; namespace Mocument.DataAccess { /// <summary> /// for controlled testing only. not threadsafe and is filebased so extreme load is not advised. /// ABSOLUTELY NOT SUITABLE FOR MULTIPROCESS ACCESS /// </summary> public class JsonFileStore : IStore { private readonly bool _deleteFileOnDispose; private readonly string _filepath; private readonly object _lockObject; private bool _disposed; private List<Tape> _list; public JsonFileStore() { _lockObject = new object(); _filepath = Path.GetTempFileName(); _deleteFileOnDispose = true; EnsureDatabase(); } public JsonFileStore(string filepath) { _lockObject = new object(); _filepath = filepath; EnsureDatabase(); } #region IStore Members public void ClearDatabase() { lock (_lockObject) { _list.Clear(); WriteJson(); } } public void EnsureDatabase() { lock (_lockObject) { try { ReadJson(); } catch (Exception) { _list = new List<Tape>(); WriteJson(); } } } public void Delete(string id) { lock (_lockObject) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id"); } Tape existing = _list.FirstOrDefault(t => t.Id == id); if (existing == null) { throw new Exception("cannot find key"); } _list.Remove(existing); WriteJson(); } } public void Update(Tape tape) { lock (_lockObject) { if (string.IsNullOrEmpty(tape.Id)) { throw new ArgumentNullException("id"); } Tape existing = _list.FirstOrDefault(t => t.Id == tape.Id); if (existing == null) { throw new Exception("cannot find key"); } _list.Remove(existing); // hack in lieu of complicated cloning _list.Add(JsonConvert.DeserializeObject<Tape>(JsonConvert.SerializeObject(tape, Formatting.Indented, GetJsonSerializerSettings()), GetJsonSerializerSettings())); WriteJson(); } } public void Insert(Tape tape) { lock (_lockObject) { if (string.IsNullOrEmpty(tape.Id)) { throw new ArgumentNullException("id"); } if (Select(tape.Id) != null) { throw new Exception("cannot insert duplicate key"); } // hack in lieu of complicated cloning _list.Add(JsonConvert.DeserializeObject<Tape>(JsonConvert.SerializeObject(tape, Formatting.Indented, GetJsonSerializerSettings()), GetJsonSerializerSettings())); WriteJson(); } } public Tape Select(string id) { if (string.IsNullOrEmpty(id)) { throw new ArgumentNullException("id"); } lock (_lockObject) { return List().FirstOrDefault(t => t.Id == id); } } public List<Tape> List() { lock (_lockObject) { // we want to return cloned tapes, not references to those in list. // so short of writing clone logic, just roundtrip the list through json serialization return JsonConvert.DeserializeObject<List<Tape>>(JsonConvert.SerializeObject(_list, Formatting.Indented, GetJsonSerializerSettings()), GetJsonSerializerSettings()); } } public List<Tape> List(Func<Tape, bool> selector) { lock (_lockObject) { return List().Where(selector).ToList(); } } public Entry MatchEntry(string tapeId, Entry entryToMatch, IEntryComparer[] comparers = null) { lock (_lockObject) { Tape tape = Select(tapeId); // provide a default comparer if (comparers == null || comparers.Length == 0) { comparers = new IEntryComparer[] { new DefaultEntryComparer() }; } List<Entry> potentialMatches = tape.log.entries; return ( from entryComparer in comparers select entryComparer.FindMatch(potentialMatches, entryToMatch) into result where result.Match != null select result.Match) .FirstOrDefault(); } } public void FromJson(string json) { lock (_lockObject) { _list = JsonConvert.DeserializeObject<List<Tape>>(json, GetJsonSerializerSettings()); if (_list == null) { throw new Exception("invalid json"); } WriteJson(); } } public string ToJson() { string json = JsonConvert.SerializeObject(_list, Formatting.Indented,GetJsonSerializerSettings()); return json; } private static JsonSerializerSettings GetJsonSerializerSettings() { return new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; } public void Dispose() { if (_disposed) { return; } _disposed = true; if (_deleteFileOnDispose) { File.Delete(_filepath); } else { WriteJson(); } } #endregion private void ReadJson() { lock (_lockObject) { FromJson(File.ReadAllText(_filepath)); } } private void WriteJson() { lock (_lockObject) { File.WriteAllText(_filepath, ToJson()); } } } }