context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** Purpose: This class will encapsulate an unsigned long and ** provide an Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { // Wrapper for unsigned 64 bit integers. [CLSCompliant(false)] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct UInt64 : IComparable, IFormattable, IComparable<UInt64>, IEquatable<UInt64>, IConvertible { private ulong m_value; // Do not rename (binary serialization) public const ulong MaxValue = (ulong)0xffffffffffffffffL; public const ulong MinValue = 0x0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt64, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt64) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. ulong i = (ulong)value; if (m_value < i) return -1; if (m_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeUInt64); } public int CompareTo(UInt64 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (m_value < value) return -1; if (m_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is UInt64)) { return false; } return m_value == ((UInt64)obj).m_value; } [NonVersionable] public bool Equals(UInt64 obj) { return m_value == obj; } // The value of the lower 32 bits XORed with the uppper 32 bits. public override int GetHashCode() { return ((int)m_value) ^ (int)(m_value >> 32); } public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(m_value, null, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(m_value, null, provider); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(m_value, format, null); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt64(m_value, format, provider); } [CLSCompliant(false)] public static ulong Parse(String s) { return FormatProvider.ParseUInt64(s, NumberStyles.Integer, null); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseUInt64(s, style, null); } [CLSCompliant(false)] public static ulong Parse(string s, IFormatProvider provider) { return FormatProvider.ParseUInt64(s, NumberStyles.Integer, provider); } [CLSCompliant(false)] public static ulong Parse(String s, NumberStyles style, IFormatProvider provider) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.ParseUInt64(s, style, provider); } [CLSCompliant(false)] public static Boolean TryParse(String s, out UInt64 result) { return FormatProvider.TryParseUInt64(s, NumberStyles.Integer, null, out result); } [CLSCompliant(false)] public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result) { UInt32.ValidateParseStyleInteger(style); return FormatProvider.TryParseUInt64(s, style, provider, out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt64; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return m_value; } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections.Generic; using System.IO; using ExtensionLoader; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenMetaverse.Packets; namespace Simian.Extensions { public class AssetManager : IExtension<Simian>, IAssetProvider { public const string UPLOAD_DIR = "uploadedAssets"; Simian server; Dictionary<UUID, Asset> AssetStore = new Dictionary<UUID, Asset>(); Dictionary<ulong, Asset> CurrentUploads = new Dictionary<ulong, Asset>(); string UploadDir; public AssetManager() { } public void Start(Simian server) { this.server = server; UploadDir = Path.Combine(server.DataDir, UPLOAD_DIR); // Try to create the data directories if they don't already exist if (!Directory.Exists(server.DataDir)) { try { Directory.CreateDirectory(server.DataDir); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Warning, ex); } } if (!Directory.Exists(UploadDir)) { try { Directory.CreateDirectory(UploadDir); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Warning, ex); } } LoadAssets(server.DataDir); LoadAssets(UploadDir); server.UDP.RegisterPacketCallback(PacketType.AssetUploadRequest, new PacketCallback(AssetUploadRequestHandler)); server.UDP.RegisterPacketCallback(PacketType.SendXferPacket, new PacketCallback(SendXferPacketHandler)); server.UDP.RegisterPacketCallback(PacketType.AbortXfer, new PacketCallback(AbortXferHandler)); server.UDP.RegisterPacketCallback(PacketType.TransferRequest, new PacketCallback(TransferRequestHandler)); } public void Stop() { } public void StoreAsset(Asset asset) { if (asset is AssetTexture) { AssetTexture texture = (AssetTexture)asset; if (texture.DecodeLayerBoundaries()) { lock (AssetStore) AssetStore[asset.AssetID] = texture; if (!asset.Temporary) SaveAsset(texture); } else { Logger.Log(String.Format("Failed to decoded layer boundaries on texture {0}", texture.AssetID), Helpers.LogLevel.Warning); } } else { if (asset.Decode()) { lock (AssetStore) AssetStore[asset.AssetID] = asset; if (!asset.Temporary) SaveAsset(asset); } else { Logger.Log(String.Format("Failed to decode {0} asset {1}", asset.AssetType, asset.AssetID), Helpers.LogLevel.Warning); } } } public bool TryGetAsset(UUID id, out Asset asset) { return AssetStore.TryGetValue(id, out asset); } #region Xfer System void AssetUploadRequestHandler(Packet packet, Agent agent) { AssetUploadRequestPacket request = (AssetUploadRequestPacket)packet; UUID assetID = UUID.Combine(request.AssetBlock.TransactionID, agent.SecureSessionID); // Check if the asset is small enough to fit in a single packet if (request.AssetBlock.AssetData.Length != 0) { // Create a new asset from the completed upload Asset asset = CreateAsset((AssetType)request.AssetBlock.Type, assetID, request.AssetBlock.AssetData); if (asset == null) { Logger.Log("Failed to create asset from uploaded data", Helpers.LogLevel.Warning); return; } Logger.DebugLog(String.Format("Storing uploaded asset {0} ({1})", assetID, asset.AssetType)); asset.Temporary = (request.AssetBlock.Tempfile | request.AssetBlock.StoreLocal); // Store the asset StoreAsset(asset); // Send a success response AssetUploadCompletePacket complete = new AssetUploadCompletePacket(); complete.AssetBlock.Success = true; complete.AssetBlock.Type = request.AssetBlock.Type; complete.AssetBlock.UUID = assetID; server.UDP.SendPacket(agent.AgentID, complete, PacketCategory.Inventory); } else { // Create a new (empty) asset for the upload Asset asset = CreateAsset((AssetType)request.AssetBlock.Type, assetID, null); if (asset == null) { Logger.Log("Failed to create asset from uploaded data", Helpers.LogLevel.Warning); return; } Logger.DebugLog(String.Format("Starting upload for {0} ({1})", assetID, asset.AssetType)); asset.Temporary = (request.AssetBlock.Tempfile | request.AssetBlock.StoreLocal); RequestXferPacket xfer = new RequestXferPacket(); xfer.XferID.DeleteOnCompletion = request.AssetBlock.Tempfile; xfer.XferID.FilePath = 0; xfer.XferID.Filename = new byte[0]; xfer.XferID.ID = request.AssetBlock.TransactionID.GetULong(); xfer.XferID.UseBigPackets = false; xfer.XferID.VFileID = asset.AssetID; xfer.XferID.VFileType = request.AssetBlock.Type; // Add this asset to the current upload list lock (CurrentUploads) CurrentUploads[xfer.XferID.ID] = asset; server.UDP.SendPacket(agent.AgentID, xfer, PacketCategory.Inventory); } } void SendXferPacketHandler(Packet packet, Agent agent) { SendXferPacketPacket xfer = (SendXferPacketPacket)packet; Asset asset; if (CurrentUploads.TryGetValue(xfer.XferID.ID, out asset)) { if (asset.AssetData == null) { if (xfer.XferID.Packet != 0) { Logger.Log(String.Format("Received Xfer packet {0} before the first packet!", xfer.XferID.Packet), Helpers.LogLevel.Error); return; } uint size = Utils.BytesToUInt(xfer.DataPacket.Data); asset.AssetData = new byte[size]; Buffer.BlockCopy(xfer.DataPacket.Data, 4, asset.AssetData, 0, xfer.DataPacket.Data.Length - 4); // Confirm the first upload packet ConfirmXferPacketPacket confirm = new ConfirmXferPacketPacket(); confirm.XferID.ID = xfer.XferID.ID; confirm.XferID.Packet = xfer.XferID.Packet; server.UDP.SendPacket(agent.AgentID, confirm, PacketCategory.Asset); } else { Buffer.BlockCopy(xfer.DataPacket.Data, 0, asset.AssetData, (int)xfer.XferID.Packet * 1000, xfer.DataPacket.Data.Length); // Confirm this upload packet ConfirmXferPacketPacket confirm = new ConfirmXferPacketPacket(); confirm.XferID.ID = xfer.XferID.ID; confirm.XferID.Packet = xfer.XferID.Packet; server.UDP.SendPacket(agent.AgentID, confirm, PacketCategory.Asset); if ((xfer.XferID.Packet & (uint)0x80000000) != 0) { // Asset upload finished Logger.DebugLog(String.Format("Completed Xfer upload of asset {0} ({1}", asset.AssetID, asset.AssetType)); lock (CurrentUploads) CurrentUploads.Remove(xfer.XferID.ID); StoreAsset(asset); AssetUploadCompletePacket complete = new AssetUploadCompletePacket(); complete.AssetBlock.Success = true; complete.AssetBlock.Type = (sbyte)asset.AssetType; complete.AssetBlock.UUID = asset.AssetID; server.UDP.SendPacket(agent.AgentID, complete, PacketCategory.Asset); } } } else { Logger.DebugLog("Received a SendXferPacket for an unknown upload"); } } void AbortXferHandler(Packet packet, Agent agent) { AbortXferPacket abort = (AbortXferPacket)packet; lock (CurrentUploads) { if (CurrentUploads.ContainsKey(abort.XferID.ID)) { Logger.DebugLog(String.Format("Aborting Xfer {0}, result: {1}", abort.XferID.ID, (TransferError)abort.XferID.Result)); CurrentUploads.Remove(abort.XferID.ID); } else { Logger.DebugLog(String.Format("Received an AbortXfer for an unknown xfer {0}", abort.XferID.ID)); } } } #endregion Xfer System #region Transfer System void TransferRequestHandler(Packet packet, Agent agent) { TransferRequestPacket request = (TransferRequestPacket)packet; ChannelType channel = (ChannelType)request.TransferInfo.ChannelType; SourceType source = (SourceType)request.TransferInfo.SourceType; if (channel == ChannelType.Asset) { // Construct the response packet TransferInfoPacket response = new TransferInfoPacket(); response.TransferInfo = new TransferInfoPacket.TransferInfoBlock(); response.TransferInfo.TransferID = request.TransferInfo.TransferID; if (source == SourceType.Asset) { // Parse the request UUID assetID = new UUID(request.TransferInfo.Params, 0); AssetType type = (AssetType)(sbyte)Utils.BytesToInt(request.TransferInfo.Params, 16); // Set the response channel type response.TransferInfo.ChannelType = (int)ChannelType.Asset; // Params response.TransferInfo.Params = new byte[20]; Buffer.BlockCopy(assetID.GetBytes(), 0, response.TransferInfo.Params, 0, 16); Buffer.BlockCopy(Utils.IntToBytes((int)type), 0, response.TransferInfo.Params, 16, 4); // Check if we have this asset Asset asset; if (AssetStore.TryGetValue(assetID, out asset)) { if (asset.AssetType == type) { Logger.DebugLog(String.Format("Transferring asset {0} ({1})", asset.AssetID, asset.AssetType)); // Asset found response.TransferInfo.Size = asset.AssetData.Length; response.TransferInfo.Status = (int)StatusCode.OK; response.TransferInfo.TargetType = (int)TargetType.Unknown; // Doesn't seem to be used by the client server.UDP.SendPacket(agent.AgentID, response, PacketCategory.Asset); // Transfer system does not wait for ACKs, just sends all of the // packets for this transfer out const int MAX_CHUNK_SIZE = Settings.MAX_PACKET_SIZE - 100; int processedLength = 0; int packetNum = 0; while (processedLength < asset.AssetData.Length) { TransferPacketPacket transfer = new TransferPacketPacket(); transfer.TransferData.ChannelType = (int)ChannelType.Asset; transfer.TransferData.TransferID = request.TransferInfo.TransferID; transfer.TransferData.Packet = packetNum++; int chunkSize = Math.Min(asset.AssetData.Length - processedLength, MAX_CHUNK_SIZE); transfer.TransferData.Data = new byte[chunkSize]; Buffer.BlockCopy(asset.AssetData, processedLength, transfer.TransferData.Data, 0, chunkSize); processedLength += chunkSize; if (processedLength >= asset.AssetData.Length) transfer.TransferData.Status = (int)StatusCode.Done; else transfer.TransferData.Status = (int)StatusCode.OK; server.UDP.SendPacket(agent.AgentID, transfer, PacketCategory.Asset); } } else { Logger.Log(String.Format( "Request for asset {0} with type {1} does not match actual asset type {2}", assetID, type, asset.AssetType), Helpers.LogLevel.Warning); } } else { Logger.Log(String.Format("Request for missing asset {0} with type {1}", assetID, type), Helpers.LogLevel.Warning); // Asset not found response.TransferInfo.Size = 0; response.TransferInfo.Status = (int)StatusCode.UnknownSource; response.TransferInfo.TargetType = (int)TargetType.Unknown; server.UDP.SendPacket(agent.AgentID, response, PacketCategory.Asset); } } else if (source == SourceType.SimEstate) { UUID agentID = new UUID(request.TransferInfo.Params, 0); UUID sessionID = new UUID(request.TransferInfo.Params, 16); EstateAssetType type = (EstateAssetType)Utils.BytesToInt(request.TransferInfo.Params, 32); Logger.Log("Please implement estate asset transfers", Helpers.LogLevel.Warning); } else if (source == SourceType.SimInventoryItem) { UUID agentID = new UUID(request.TransferInfo.Params, 0); UUID sessionID = new UUID(request.TransferInfo.Params, 16); UUID ownerID = new UUID(request.TransferInfo.Params, 32); UUID taskID = new UUID(request.TransferInfo.Params, 48); UUID itemID = new UUID(request.TransferInfo.Params, 64); UUID assetID = new UUID(request.TransferInfo.Params, 80); AssetType type = (AssetType)(sbyte)Utils.BytesToInt(request.TransferInfo.Params, 96); if (taskID != UUID.Zero) { // Task (prim) inventory request Logger.Log("Please implement task inventory transfers", Helpers.LogLevel.Warning); } else { // Agent inventory request Logger.Log("Please implement agent inventory transfer", Helpers.LogLevel.Warning); } } else { Logger.Log(String.Format( "Received a TransferRequest that we don't know how to handle. Channel: {0}, Source: {1}", channel, source), Helpers.LogLevel.Warning); } } else { Logger.Log(String.Format( "Received a TransferRequest that we don't know how to handle. Channel: {0}, Source: {1}", channel, source), Helpers.LogLevel.Warning); } } #endregion Transfer System void SaveAsset(Asset asset) { try { File.WriteAllBytes(Path.Combine(UploadDir, String.Format("{0}.{1}", asset.AssetID, asset.AssetType.ToString().ToLower())), asset.AssetData); } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Warning, ex); } } Asset CreateAsset(AssetType type, UUID assetID, byte[] data) { switch (type) { case AssetType.Bodypart: return new AssetBodypart(assetID, data); case AssetType.Clothing: return new AssetClothing(assetID, data); case AssetType.LSLBytecode: return new AssetScriptBinary(assetID, data); case AssetType.LSLText: return new AssetScriptText(assetID, data); case AssetType.Notecard: return new AssetNotecard(assetID, data); case AssetType.Texture: return new AssetTexture(assetID, data); case AssetType.Animation: return new AssetAnimation(assetID, data); case AssetType.CallingCard: case AssetType.Folder: case AssetType.Gesture: case AssetType.ImageJPEG: case AssetType.ImageTGA: case AssetType.Landmark: case AssetType.LostAndFoundFolder: case AssetType.Object: case AssetType.RootFolder: case AssetType.Simstate: case AssetType.SnapshotFolder: case AssetType.Sound: return new AssetSound(assetID, data); case AssetType.SoundWAV: case AssetType.TextureTGA: case AssetType.TrashFolder: case AssetType.Unknown: default: Logger.Log("Asset type " + type.ToString() + " not implemented!", Helpers.LogLevel.Warning); return null; } } void LoadAssets(string path) { try { string[] textures = Directory.GetFiles(path, "*.jp2", SearchOption.TopDirectoryOnly); string[] clothing = Directory.GetFiles(path, "*.clothing", SearchOption.TopDirectoryOnly); string[] bodyparts = Directory.GetFiles(path, "*.bodypart", SearchOption.TopDirectoryOnly); string[] sounds = Directory.GetFiles(path, "*.ogg", SearchOption.TopDirectoryOnly); for (int i = 0; i < textures.Length; i++) { UUID assetID = ParseUUIDFromFilename(textures[i]); Asset asset = new AssetTexture(assetID, File.ReadAllBytes(textures[i])); asset.Temporary = true; StoreAsset(asset); } for (int i = 0; i < clothing.Length; i++) { UUID assetID = ParseUUIDFromFilename(clothing[i]); Asset asset = new AssetClothing(assetID, File.ReadAllBytes(clothing[i])); asset.Temporary = true; StoreAsset(asset); } for (int i = 0; i < bodyparts.Length; i++) { UUID assetID = ParseUUIDFromFilename(bodyparts[i]); Asset asset = new AssetBodypart(assetID, File.ReadAllBytes(bodyparts[i])); asset.Temporary = true; StoreAsset(asset); } for (int i = 0; i < sounds.Length; i++) { UUID assetID = ParseUUIDFromFilename(sounds[i]); Asset asset = new AssetSound(assetID, File.ReadAllBytes(sounds[i])); asset.Temporary = true; StoreAsset(asset); } } catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Warning, ex); } } static UUID ParseUUIDFromFilename(string filename) { int dot = filename.LastIndexOf('.'); if (dot > 35) { // Grab the last 36 characters of the filename string uuidString = filename.Substring(dot - 36, 36); UUID uuid; UUID.TryParse(uuidString, out uuid); return uuid; } else { return UUID.Zero; } } } }
// 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 Xunit; namespace System.Collections.Tests { public static class BitArray_CtorTests { private const int BitsPerByte = 8; private const int BitsPerInt32 = 32; [Theory] [InlineData(0)] [InlineData(1)] [InlineData(BitsPerByte)] [InlineData(BitsPerByte * 2)] [InlineData(BitsPerInt32)] [InlineData(BitsPerInt32 * 2)] [InlineData(200)] [InlineData(65551)] public static void Ctor_Int(int length) { BitArray bitArray = new BitArray(length); Assert.Equal(length, bitArray.Length); for (int i = 0; i < bitArray.Length; i++) { Assert.False(bitArray[i]); Assert.False(bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(length, collection.Count); Assert.False(collection.IsSynchronized); } [Theory] [InlineData(0, true)] [InlineData(0, false)] [InlineData(1, true)] [InlineData(1, false)] [InlineData(BitsPerByte, true)] [InlineData(BitsPerByte, false)] [InlineData(BitsPerByte * 2, true)] [InlineData(BitsPerByte * 2, false)] [InlineData(BitsPerInt32, true)] [InlineData(BitsPerInt32, false)] [InlineData(BitsPerInt32 * 2, true)] [InlineData(BitsPerInt32 * 2, false)] [InlineData(200, true)] [InlineData(200, false)] [InlineData(65551, true)] [InlineData(65551, false)] public static void Ctor_Int_Bool(int length, bool defaultValue) { BitArray bitArray = new BitArray(length, defaultValue); Assert.Equal(length, bitArray.Length); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(defaultValue, bitArray[i]); Assert.Equal(defaultValue, bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(length, collection.Count); Assert.False(collection.IsSynchronized); } [Fact] public static void Ctor_Int_NegativeLength_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => new BitArray(-1, false)); } public static IEnumerable<object[]> Ctor_BoolArray_TestData() { yield return new object[] { new bool[0] }; foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { yield return new object[] { Enumerable.Repeat(true, size).ToArray() }; yield return new object[] { Enumerable.Repeat(false, size).ToArray() }; yield return new object[] { Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray() }; } } [Theory] [MemberData(nameof(Ctor_BoolArray_TestData))] public static void Ctor_BoolArray(bool[] values) { BitArray bitArray = new BitArray(values); Assert.Equal(values.Length, bitArray.Length); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(values[i], bitArray[i]); Assert.Equal(values[i], bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(values.Length, collection.Count); Assert.False(collection.IsSynchronized); } public static IEnumerable<object[]> Ctor_BitArray_TestData() { yield return new object[] { "bool[](empty)", new BitArray(new bool[0]) }; yield return new object[] { "byte[](empty)", new BitArray(new byte[0]) }; yield return new object[] { "int[](empty)", new BitArray(new int[0]) }; foreach (int size in new[] { 1, BitsPerByte, BitsPerByte * 2, BitsPerInt32, BitsPerInt32 * 2 }) { yield return new object[] { "length", new BitArray(size) }; yield return new object[] { "length|default(true)", new BitArray(size, true) }; yield return new object[] { "length|default(false)", new BitArray(size, false) }; yield return new object[] { "bool[](all)", new BitArray(Enumerable.Repeat(true, size).ToArray()) }; yield return new object[] { "bool[](none)", new BitArray(Enumerable.Repeat(false, size).ToArray()) }; yield return new object[] { "bool[](alternating)", new BitArray(Enumerable.Range(0, size).Select(x => x % 2 == 0).ToArray()) }; if (size >= BitsPerByte) { yield return new object[] { "byte[](all)", new BitArray(Enumerable.Repeat((byte)0xff, size / BitsPerByte).ToArray()) }; yield return new object[] { "byte[](none)", new BitArray(Enumerable.Repeat((byte)0x00, size / BitsPerByte).ToArray()) }; yield return new object[] { "byte[](alternating)", new BitArray(Enumerable.Repeat((byte)0xaa, size / BitsPerByte).ToArray()) }; } if (size >= BitsPerInt32) { yield return new object[] { "int[](all)", new BitArray(Enumerable.Repeat(unchecked((int)0xffffffff), size / BitsPerInt32).ToArray()) }; yield return new object[] { "int[](none)", new BitArray(Enumerable.Repeat(0x00000000, size / BitsPerInt32).ToArray()) }; yield return new object[] { "int[](alternating)", new BitArray(Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size / BitsPerInt32).ToArray()) }; } } } [Theory] [MemberData(nameof(Ctor_BitArray_TestData))] public static void Ctor_BitArray(string label, BitArray bits) { BitArray bitArray = new BitArray(bits); Assert.Equal(bits.Length, bitArray.Length); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(bits[i], bitArray[i]); Assert.Equal(bits[i], bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(bits.Length, collection.Count); Assert.False(collection.IsSynchronized); } public static IEnumerable<object[]> Ctor_IntArray_TestData() { yield return new object[] { new int[0], new bool[0] }; foreach (int size in new[] { 1, 10 }) { yield return new object[] { Enumerable.Repeat(unchecked((int)0xffffffff), size).ToArray(), Enumerable.Repeat(true, size * BitsPerInt32).ToArray() }; yield return new object[] { Enumerable.Repeat(0x00000000, size).ToArray(), Enumerable.Repeat(false, size * BitsPerInt32).ToArray() }; yield return new object[] { Enumerable.Repeat(unchecked((int)0xaaaaaaaa), size).ToArray(), Enumerable.Range(0, size * BitsPerInt32).Select(i => i % 2 == 1).ToArray() }; } } [Theory] [MemberData(nameof(Ctor_IntArray_TestData))] public static void Ctor_IntArray(int[] array, bool[] expected) { BitArray bitArray = new BitArray(array); Assert.Equal(expected.Length, bitArray.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], bitArray[i]); Assert.Equal(expected[i], bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(expected.Length, collection.Count); Assert.False(collection.IsSynchronized); } [Fact] public static void Ctor_BitArray_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("bits", () => new BitArray((BitArray)null)); } [Fact] public static void Ctor_BoolArray_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("values", () => new BitArray((bool[])null)); } [Fact] public static void Ctor_IntArray_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("values", () => new BitArray((int[])null)); } public static IEnumerable<object[]> Ctor_ByteArray_TestData() { yield return new object[] { new byte[0], new bool[0] }; foreach (int size in new[] { 1, 2, BitsPerInt32 / BitsPerByte, 2 * BitsPerInt32 / BitsPerByte }) { yield return new object[] { Enumerable.Repeat((byte)0xff, size).ToArray(), Enumerable.Repeat(true, size * BitsPerByte).ToArray() }; yield return new object[] { Enumerable.Repeat((byte)0x00, size).ToArray(), Enumerable.Repeat(false, size * BitsPerByte).ToArray() }; yield return new object[] { Enumerable.Repeat((byte)0xaa, size).ToArray(), Enumerable.Range(0, size * BitsPerByte).Select(i => i % 2 == 1).ToArray() }; } } [Theory] [MemberData(nameof(Ctor_ByteArray_TestData))] public static void Ctor_ByteArray(byte[] bytes, bool[] expected) { BitArray bitArray = new BitArray(bytes); Assert.Equal(expected.Length, bitArray.Length); for (int i = 0; i < bitArray.Length; i++) { Assert.Equal(expected[i], bitArray[i]); Assert.Equal(expected[i], bitArray.Get(i)); } ICollection collection = bitArray; Assert.Equal(expected.Length, collection.Count); Assert.False(collection.IsSynchronized); } [Fact] public static void Ctor_ByteArray_Null_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("bytes", () => new BitArray((byte[])null)); } } }
using System; using PcapDotNet.Base; namespace PcapDotNet.Packets.IpV4 { /// <summary> /// This option identifies the U.S. classification level at which the datagram is to be protected /// and the authorities whose protection rules apply to each datagram. /// /// <para> /// This option is used by end systems and intermediate systems of an internet to: /// <list type="number"> /// <item>Transmit from source to destination in a network standard representation the common security labels required by computer security models.</item> /// <item>Validate the datagram as appropriate for transmission from the source and delivery to the destination.</item> /// <item> /// Ensure that the route taken by the datagram is protected to the level required by all protection authorities indicated on the datagram. /// In order to provide this facility in a general Internet environment, interior and exterior gateway protocols must be augmented /// to include security label information in support of routing control. /// </item> /// </list> /// </para> /// /// <para> /// The DoD Basic Security option must be copied on fragmentation. /// This option appears at most once in a datagram. /// Some security systems require this to be the first option if more than one option is carried in the IP header, /// but this is not a generic requirement levied by this specification. /// </para> /// /// <para> /// The format of the DoD Basic Security option is as follows: /// <pre> /// +------------+------------+------------+-------------//----------+ /// | 10000010 | XXXXXXXX | SSSSSSSS | AAAAAAA[1] AAAAAAA0 | /// | | | | [0] | /// +------------+------------+------------+-------------//----------+ /// TYPE = 130 LENGTH CLASSIFICATION PROTECTION /// LEVEL AUTHORITY /// FLAGS /// </pre> /// </para> /// </summary> [OptionTypeRegistration(typeof(IpV4OptionType), IpV4OptionType.BasicSecurity)] public sealed class IpV4OptionBasicSecurity : IpV4OptionComplex, IOptionComplexFactory, IEquatable<IpV4OptionBasicSecurity> { /// <summary> /// The minimum number of bytes this option take. /// </summary> public const int OptionMinimumLength = 3; /// <summary> /// The minimum number of bytes this option's value take. /// </summary> public const int OptionValueMinimumLength = OptionMinimumLength - OptionHeaderLength; /// <summary> /// Create the security option from the different security field values. /// </summary> /// <param name="classificationLevel"> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </param> /// <param name="protectionAuthorities"> /// This field identifies the National Access Programs or Special Access Programs /// which specify protection rules for transmission and processing of the information contained in the datagram. /// </param> /// <param name="length"> /// The number of bytes this option will take. /// </param> public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel, IpV4OptionSecurityProtectionAuthorities protectionAuthorities, byte length) : base(IpV4OptionType.BasicSecurity) { if (length < OptionMinimumLength) throw new ArgumentOutOfRangeException("length", length, "Minimum option length is " + OptionMinimumLength); if (length == OptionMinimumLength && protectionAuthorities != IpV4OptionSecurityProtectionAuthorities.None) { throw new ArgumentException("Can't have a protection authority without minimum of " + (OptionValueMinimumLength + 1) + " length", "protectionAuthorities"); } if (classificationLevel != IpV4OptionSecurityClassificationLevel.Confidential && classificationLevel != IpV4OptionSecurityClassificationLevel.Secret && classificationLevel != IpV4OptionSecurityClassificationLevel.TopSecret && classificationLevel != IpV4OptionSecurityClassificationLevel.Unclassified) { throw new ArgumentException("Invalid classification level " + classificationLevel); } _classificationLevel = classificationLevel; _protectionAuthorities = protectionAuthorities; _length = length; } /// <summary> /// Create the security option with only classification level. /// </summary> /// <param name="classificationLevel"> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </param> public IpV4OptionBasicSecurity(IpV4OptionSecurityClassificationLevel classificationLevel) : this(classificationLevel, IpV4OptionSecurityProtectionAuthorities.None, OptionMinimumLength) { } /// <summary> /// Creates unclassified security option. /// </summary> public IpV4OptionBasicSecurity() : this(IpV4OptionSecurityClassificationLevel.Unclassified) { } /// <summary> /// This field specifies the (U.S.) classification level at which the datagram must be protected. /// The information in the datagram must be protected at this level. /// </summary> public IpV4OptionSecurityClassificationLevel ClassificationLevel { get { return _classificationLevel; } } /// <summary> /// This field identifies the National Access Programs or Special Access Programs /// which specify protection rules for transmission and processing of the information contained in the datagram. /// </summary> public IpV4OptionSecurityProtectionAuthorities ProtectionAuthorities { get { return _protectionAuthorities; } } /// <summary> /// The number of bytes this option will take. /// </summary> public override int Length { get { return _length; } } /// <summary> /// True iff this option may appear at most once in a datagram. /// </summary> public override bool IsAppearsAtMostOnce { get { return true; } } /// <summary> /// Two security options are equal iff they have the exact same field values. /// </summary> public bool Equals(IpV4OptionBasicSecurity other) { if (other == null) return false; return ClassificationLevel == other.ClassificationLevel && ProtectionAuthorities == other.ProtectionAuthorities && Length == other.Length; } /// <summary> /// Two security options are equal iff they have the exact same field values. /// </summary> public override bool Equals(IpV4Option other) { return Equals(other as IpV4OptionBasicSecurity); } /// <summary> /// The hash code is the xor of the base class hash code /// with the hash code of the combination of the classification level, protection authority and length. /// </summary> /// <returns></returns> public override int GetHashCode() { return base.GetHashCode() ^ BitSequence.Merge((byte)ClassificationLevel, (byte)ProtectionAuthorities,(byte)Length).GetHashCode(); } /// <summary> /// Tries to read the option from a buffer starting from the option value (after the type and length). /// </summary> /// <param name="buffer">The buffer to read the option from.</param> /// <param name="offset">The offset to the first byte to read the buffer. Will be incremented by the number of bytes read.</param> /// <param name="valueLength">The number of bytes the option value should take according to the length field that was already read.</param> /// <returns>On success - the complex option read. On failure - null.</returns> Option IOptionComplexFactory.CreateInstance(byte[] buffer, ref int offset, byte valueLength) { // if (buffer == null) // throw new ArgumentNullException("buffer"); if (valueLength < OptionValueMinimumLength) return null; // Classification level IpV4OptionSecurityClassificationLevel classificationLevel = (IpV4OptionSecurityClassificationLevel)buffer[offset++]; if (classificationLevel != IpV4OptionSecurityClassificationLevel.Confidential && classificationLevel != IpV4OptionSecurityClassificationLevel.Secret && classificationLevel != IpV4OptionSecurityClassificationLevel.TopSecret && classificationLevel != IpV4OptionSecurityClassificationLevel.Unclassified) { return null; } // Protection authorities int protectionAuthoritiesLength = valueLength - OptionValueMinimumLength; IpV4OptionSecurityProtectionAuthorities protectionAuthorities = IpV4OptionSecurityProtectionAuthorities.None; if (protectionAuthoritiesLength > 0) { for (int i = 0; i < protectionAuthoritiesLength - 1; ++i) { if ((buffer[offset + i] & 0x01) == 0) return null; } if ((buffer[offset + protectionAuthoritiesLength - 1] & 0x01) != 0) return null; protectionAuthorities = (IpV4OptionSecurityProtectionAuthorities)(buffer[offset] & 0xFE); } offset += protectionAuthoritiesLength; return new IpV4OptionBasicSecurity(classificationLevel, protectionAuthorities, (byte)(OptionMinimumLength + protectionAuthoritiesLength)); } internal override void Write(byte[] buffer, ref int offset) { base.Write(buffer, ref offset); buffer[offset++] = (byte)ClassificationLevel; int protectionAuthorityLength = Length - OptionMinimumLength; if (protectionAuthorityLength > 0) { buffer[offset++] = (byte)ProtectionAuthorities; if (protectionAuthorityLength > 1) { buffer[offset - 1] |= 0x01; for (int i = 0; i != protectionAuthorityLength - 2; ++i) buffer[offset++] = 0x01; buffer[offset++] = 0x00; } } } private readonly IpV4OptionSecurityClassificationLevel _classificationLevel; private readonly IpV4OptionSecurityProtectionAuthorities _protectionAuthorities; private readonly byte _length; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { /// <summary> /// Keeps track of the rename tracking state for a given text buffer by tracking its /// changes over time. /// </summary> private class StateMachine : ForegroundThreadAffinitizedObject { private readonly IInlineRenameService _inlineRenameService; private readonly IAsynchronousOperationListener _asyncListener; private readonly ITextBuffer _buffer; private readonly IDiagnosticAnalyzerService _diagnosticAnalyzerService; private int _refCount; public TrackingSession TrackingSession { get; private set; } public ITextBuffer Buffer { get { return _buffer; } } public event Action TrackingSessionUpdated = delegate { }; public event Action<ITrackingSpan> TrackingSessionCleared = delegate { }; public StateMachine( ITextBuffer buffer, IInlineRenameService inlineRenameService, IAsynchronousOperationListener asyncListener, IDiagnosticAnalyzerService diagnosticAnalyzerService) { _buffer = buffer; _buffer.Changed += Buffer_Changed; _inlineRenameService = inlineRenameService; _asyncListener = asyncListener; _diagnosticAnalyzerService = diagnosticAnalyzerService; } private void Buffer_Changed(object sender, TextContentChangedEventArgs e) { AssertIsForeground(); if (!_buffer.GetOption(InternalFeatureOnOffOptions.RenameTracking)) { // When disabled, ignore all text buffer changes and do not trigger retagging return; } using (Logger.LogBlock(FunctionId.Rename_Tracking_BufferChanged, CancellationToken.None)) { // When the buffer changes, several things might be happening: // 1. If a non-identifer character has been added or deleted, we stop tracking // completely. // 2. Otherwise, if the changes are completely contained an existing session, then // continue that session. // 3. Otherwise, we're starting a new tracking session. Find and track the span of // the relevant word in the foreground, and use a task to figure out whether the // original word was a renamable identifier or not. if (e.Changes.Count != 1 || ShouldClearTrackingSession(e.Changes.Single())) { ClearTrackingSession(); return; } // The change is trackable. Figure out whether we should continue an existing // session var change = e.Changes.Single(); if (this.TrackingSession == null) { StartTrackingSession(e); return; } // There's an existing session. Continue that session if the current change is // contained inside the tracking span. SnapshotSpan trackingSpanInNewSnapshot = this.TrackingSession.TrackingSpan.GetSpan(e.After); if (trackingSpanInNewSnapshot.Contains(change.NewSpan)) { // Continuing an existing tracking session. If there may have been a tag // showing, then update the tags. if (this.TrackingSession.IsDefinitelyRenamableIdentifier()) { this.TrackingSession.CheckNewIdentifier(this, _buffer.CurrentSnapshot); TrackingSessionUpdated(); } } else { StartTrackingSession(e); } } } private bool ShouldClearTrackingSession(ITextChange change) { AssertIsForeground(); ISyntaxFactsService syntaxFactsService; if (!TryGetSyntaxFactsService(out syntaxFactsService)) { return true; } // The editor will replace virtual space with spaces and/or tabs when typing on a // previously blank line. Trim these characters from the start of change.NewText. If // the resulting change is empty (the user just typed a <space>), clear the session. var changedText = change.OldText + change.NewText.TrimStart(' ', '\t'); if (changedText.IsEmpty()) { return true; } return changedText.Any(c => !IsTrackableCharacter(syntaxFactsService, c)); } private void StartTrackingSession(TextContentChangedEventArgs eventArgs) { AssertIsForeground(); ClearTrackingSession(); if (_inlineRenameService.ActiveSession != null) { return; } // Synchronously find the tracking span in the old document. var change = eventArgs.Changes.Single(); var beforeText = eventArgs.Before.AsText(); ISyntaxFactsService syntaxFactsService; if (!TryGetSyntaxFactsService(out syntaxFactsService)) { return; } int leftSidePosition = change.OldPosition; int rightSidePosition = change.OldPosition + change.OldText.Length; while (leftSidePosition > 0 && IsTrackableCharacter(syntaxFactsService, beforeText[leftSidePosition - 1])) { leftSidePosition--; } while (rightSidePosition < beforeText.Length && IsTrackableCharacter(syntaxFactsService, beforeText[rightSidePosition])) { rightSidePosition++; } var originalSpan = new Span(leftSidePosition, rightSidePosition - leftSidePosition); this.TrackingSession = new TrackingSession(this, new SnapshotSpan(eventArgs.Before, originalSpan), _asyncListener); } private bool IsTrackableCharacter(ISyntaxFactsService syntaxFactsService, char c) { // Allow identifier part characters at the beginning of strings (even if they are // not identifier start characters). If an intermediate name is not valid, the smart // tag will not be shown due to later checks. Also allow escape chars anywhere as // they might be in the middle of a complex edit. return syntaxFactsService.IsIdentifierPartCharacter(c) || syntaxFactsService.IsIdentifierEscapeCharacter(c); } public bool ClearTrackingSession() { AssertIsForeground(); if (this.TrackingSession != null) { // Disallow the existing TrackingSession from triggering IdentifierFound. var previousTrackingSession = this.TrackingSession; this.TrackingSession = null; previousTrackingSession.Cancel(); // If there may have been a tag showing, then actually clear the tags. if (previousTrackingSession.IsDefinitelyRenamableIdentifier()) { TrackingSessionCleared(previousTrackingSession.TrackingSpan); } return true; } return false; } public bool ClearVisibleTrackingSession() { AssertIsForeground(); if (this.TrackingSession != null && this.TrackingSession.IsDefinitelyRenamableIdentifier()) { var document = _buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { // When rename tracking is dismissed via escape, we no longer wish to // provide a diagnostic/codefix, but nothing has changed in the workspace // to trigger the diagnostic system to reanalyze, so we trigger it // manually. _diagnosticAnalyzerService?.Reanalyze( document.Project.Solution.Workspace, documentIds: SpecializedCollections.SingletonEnumerable(document.Id)); } // Disallow the existing TrackingSession from triggering IdentifierFound. var previousTrackingSession = this.TrackingSession; this.TrackingSession = null; previousTrackingSession.Cancel(); TrackingSessionCleared(previousTrackingSession.TrackingSpan); return true; } return false; } public bool CanInvokeRename(out TrackingSession trackingSession, bool isSmartTagCheck = false, bool waitForResult = false, CancellationToken cancellationToken = default(CancellationToken)) { // This needs to be able to run on a background thread for the diagnostic. trackingSession = this.TrackingSession; if (trackingSession == null) { return false; } ISyntaxFactsService syntaxFactsService; return TryGetSyntaxFactsService(out syntaxFactsService) && trackingSession.CanInvokeRename(syntaxFactsService, isSmartTagCheck, waitForResult, cancellationToken); } internal async Task<IEnumerable<Diagnostic>> GetDiagnostic(SyntaxTree tree, DiagnosticDescriptor diagnosticDescriptor, CancellationToken cancellationToken) { try { // This can be called on a background thread. We are being asked whether a // lightbulb should be shown for the given document, but we only know about the // current state of the buffer. Compare the text to see if we should bail early. // Even if the text is the same, the buffer may change on the UI thread during this // method. If it does, we may give an incorrect response, but the diagnostics // engine will know that the document changed and not display the lightbulb anyway. if (Buffer.AsTextContainer().CurrentText != await tree.GetTextAsync(cancellationToken).ConfigureAwait(false)) { return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } TrackingSession trackingSession; if (CanInvokeRename(out trackingSession, waitForResult: true, cancellationToken: cancellationToken)) { SnapshotSpan snapshotSpan = trackingSession.TrackingSpan.GetSpan(Buffer.CurrentSnapshot); var textSpan = snapshotSpan.Span.ToTextSpan(); var builder = ImmutableDictionary.CreateBuilder<string, string>(); builder.Add(RenameTrackingDiagnosticAnalyzer.RenameFromPropertyKey, trackingSession.OriginalName); builder.Add(RenameTrackingDiagnosticAnalyzer.RenameToPropertyKey, snapshotSpan.GetText()); var properties = builder.ToImmutable(); var diagnostic = Diagnostic.Create(diagnosticDescriptor, tree.GetLocation(textSpan), properties); return SpecializedCollections.SingletonEnumerable(diagnostic); } return SpecializedCollections.EmptyEnumerable<Diagnostic>(); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public void RestoreTrackingSession(TrackingSession trackingSession) { AssertIsForeground(); ClearTrackingSession(); this.TrackingSession = trackingSession; TrackingSessionUpdated(); } public void OnTrackingSessionUpdated(TrackingSession trackingSession) { AssertIsForeground(); if (this.TrackingSession == trackingSession) { TrackingSessionUpdated(); } } private bool TryGetSyntaxFactsService(out ISyntaxFactsService syntaxFactsService) { // Can be called on a background thread syntaxFactsService = null; var document = _buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); } return syntaxFactsService != null; } public void Connect() { AssertIsForeground(); _refCount++; } public void Disconnect() { AssertIsForeground(); _refCount--; Contract.ThrowIfFalse(_refCount >= 0); if (_refCount == 0) { this.Buffer.Properties.RemoveProperty(typeof(StateMachine)); this.Buffer.Changed -= Buffer_Changed; } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using NOps.Migrator.MigrationPoints; using NOps.Migrator.Registry; namespace NOps.Migrator { public class Migrator { private readonly IEnumerable<Type> _migrationPointTypes; private readonly IMigrationPointVersionRegistry _registry; private Stack<MigrationPointMigrator> _migrated; private readonly object _migratorLock = new object(); private readonly ProgressReport _progressMessage; public Migrator(IMigrationPointVersionRegistry registry, ProgressReport progressReport = null) : this(DetermineAssemblyMigrationPoints(Assembly.GetEntryAssembly()), registry, progressReport) { } public Migrator(Assembly migrationPointAssembly, IMigrationPointVersionRegistry registry, ProgressReport progressReport = null) : this(DetermineAssemblyMigrationPoints(migrationPointAssembly), registry, progressReport) { } public Migrator(IEnumerable<Type> migrationPointTypes, IMigrationPointVersionRegistry registry, ProgressReport progressReport = null) { _migrationPointTypes = migrationPointTypes; _registry = registry; _progressMessage = progressReport ?? ProgressReporting.NullMessageReceiver; } [DebuggerStepThrough] private void P(string format, params object[] args) { P(string.Format(format, args)); } [DebuggerStepThrough] private void P(string message) { _progressMessage(message); } internal static IEnumerable<Type> DetermineAssemblyMigrationPoints(Assembly migrationPointAssembly) { return migrationPointAssembly .GetTypes() .Where(t => typeof(IMigrationPoint).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract); } public virtual void Migrate() { lock (_migratorLock) { _migrated = new Stack<MigrationPointMigrator>(); P("Migration of MigrationPoints started."); foreach(var migrationPoint in _migrationPointTypes) { MigrateMigrationPoint(migrationPoint); } P("Migration of MigrationPoints completed."); } } public virtual bool IsDataCurrent() { bool any = false; lock (_migratorLock) { P("Checking for required migrations...."); foreach(var migrationPointType in _migrationPointTypes) { long version = 0; if(_registry.Exists(migrationPointType.Name)) { MigrationPointVersion registryEntry = _registry[migrationPointType.Name]; version = registryEntry.Version; } var dtMigrator = CreateMigrationPointMigrator(migrationPointType); long requiredVersion; if (!dtMigrator.IsMigrationPointCurrent(version, out requiredVersion)) { P("MigrationPoint '{0}' requires migration from {1} to {2}.", migrationPointType.Name, version, requiredVersion); any = true; } P("MigrationPoint '{0}' is current (version {1}).", migrationPointType.Name, version); } } if (!any) { P("All MigrationPoints are current, no migration required."); } else { P("MigrationPoints found requiring migrations."); } return !any; } private void MigrateMigrationPoint(Type migrationPoint) { long version = 0; MigrationPointVersion registryEntry = null; if(_registry.Exists(migrationPoint.Name)) { registryEntry = _registry[migrationPoint.Name]; version = registryEntry.Version; } var dtMigrator = CreateMigrationPointMigrator(migrationPoint); try { P("Migrating MigrationPoint {0} from version {1}.", migrationPoint.Name, version); long newVersion = dtMigrator.Migrate(version); if(newVersion > version) { _migrated.Push(dtMigrator); if(registryEntry == null) { _registry.Add(migrationPoint.Name, newVersion); P("Added '{0}' to the MigrationPointVersionRegistry.", migrationPoint.Name); } else { registryEntry.Version = newVersion; } _registry.Save(); } } catch(MigrationFailureException ex) { RevertPreviouslyCompletedMigrationPointMigrations(migrationPoint.Name, version, ex); // should not get here (above method always throws) throw; } } private void RevertPreviouslyCompletedMigrationPointMigrations(string migrationPointName, long attemptedVersion, Exception ex) { P("MigrationPoint migration failed, reverting."); var revertFailures = new List<Exception>(); while(_migrated.Any()) { var dtm = _migrated.Pop(); try { P("Reverting MigrationPoint {0}", dtm.MigrationPointName); dtm.Revert(); } catch(Exception revertEx) { P("Revert failed."); revertFailures.Add(revertEx); } } P("All MigrationPoints reverted."); if (revertFailures.Any()) { if (ex is UnrevertedMigrationFailureException) { throw new UnrevertedMigrationFailureException(string.Format("MigrationPoint '{0}' failed to migrate to version {1} and failed reverting. Reverted all other migrations, some of them also failed. Examine this ReversalExceptions on this exception.", migrationPointName, attemptedVersion), ex, revertFailures); } throw new UnrevertedMigrationFailureException(string.Format("MigrationPoint '{0}' failed to migrate to version {1} and succesfully reverted. Reverted all other migrations, some of them failed. Examine this ReversalExceptions on this exception.", migrationPointName, attemptedVersion), ex, revertFailures); } if (ex is UnrevertedMigrationFailureException) { throw new UnrevertedMigrationFailureException(string.Format("MigrationPoint '{0}' failed to migrate to version {1} and failed reverting. Reverted all other migrations succesfully.", migrationPointName, attemptedVersion), ex); } throw new RevertedMigrationFailureException(string.Format("MigrationPoint '{0}' failed to migrate to version {1}. Reverted all migrations succesfully.", migrationPointName, attemptedVersion), ex); } protected virtual MigrationPointMigrator CreateMigrationPointMigrator(Type migrationPoint) { return new MigrationPointMigrator(migrationPoint, _progressMessage); } } public class MigratorException : Exception { public MigratorException(string message) : base(message) { } public MigratorException(string message, Exception innerException) : base(message, innerException) { } } }
namespace FakeItEasy.Specs { using System; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public class CallDescriptionsInAssertionSpecs { public interface IFoo { int Bar(int i); int Bar(HasCustomValueFormatter x); int Bar(HasCustomValueFormatterThatReturnsNull x); int Bar(HasCustomValueFormatterThatThrows x); int Baz { get; set; } } [Scenario] public void AssertedCallDescriptionForMethod(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call is made to the fake" .x(() => { }); "When I assert that a method was called" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(42)).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Bar(i: 42)\r\n*")); } [Scenario] public void ActualCallDescriptionForMethod(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And I make a call to Bar with argument 0" .x(() => fake.Bar(42)); "When I assert that the Bar method was called with argument 42" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(0)).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the actual call that was made" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n 1: FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Bar(i: 42)\r\n*")); } [Scenario] public void AssertedCallDescriptionForPropertyGetter(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call is made to the fake" .x(() => { }); "When I assert that a property getter was called" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Baz).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz\r\n*")); } [Scenario] public void ActualCallDescriptionForPropertyGetter(IFoo fake, Exception exception, int baz) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And I make a call to a property getter" .x(() => { baz = fake.Baz; }); "When I assert that a different call was made" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(0)).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception correctly describes the actual call that was made" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n 1: FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz\r\n*")); } [Scenario] public void AssertedCallDescriptionForPropertySetterWithAnyValue(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call is made to the fake" .x(() => { }); "When I assert that a property setter was called" .x(() => exception = Record.Exception(() => A.CallToSet(() => fake.Baz).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz = <Ignored>\r\n*")); } [Scenario] public void AssertedCallDescriptionForPropertySetterWithConstantValue(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call is made to the fake" .x(() => { }); "When I assert that a property setter was called" .x(() => exception = Record.Exception(() => A.CallToSet(() => fake.Baz).To(42).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz = 42\r\n*")); } [Scenario] public void AssertedCallDescriptionForPropertySetterWithConstrainedValue(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And no call is made to the fake" .x(() => { }); "When I assert that a property setter was called" .x(() => exception = Record.Exception(() => A.CallToSet(() => fake.Baz).To(() => A<int>.That.Matches(i => i % 2 == 0, "an even number")).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz = <an even number>\r\n*")); } [Scenario] public void ActualCallDescriptionForPropertySetterWithConstantValue(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And I make a call to a property setter" .x(() => { fake.Baz = 42; }); "When I assert that a different call was made" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(0)).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception correctly describes the actual call that was made" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n 1: FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Baz = 42\r\n*")); } [Scenario] public void AssertedCallDescriptionWithCustomValueFormatter(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And the fake has a method with a parameter that has a custom argument value formatter" .See<IFoo>(foo => foo.Bar(new HasCustomValueFormatter())); "And no call is made to the fake" .x(() => { }); "When I assert that the method was called" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(new HasCustomValueFormatter())).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call, using the appropriate argument value formatter" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Bar(x: hello world)\r\n*")); } [Scenario] public void AssertedCallDescriptionWithCustomValueFormatterThatReturnsNull(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And the fake has a method with a parameter that has a custom argument value formatter that returns null" .See<IFoo>(foo => foo.Bar(new HasCustomValueFormatterThatReturnsNull())); "And no call is made to the fake" .x(() => { }); "When I assert that the method was called" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(new HasCustomValueFormatterThatReturnsNull())).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call, using the next best argument value formatter" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Bar(x: hello world)\r\n*")); } [Scenario] public void ExceptionInCustomArgumentValueFormatter(IFoo fake, Exception exception) { "Given a fake" .x(() => fake = A.Fake<IFoo>()); "And the fake has a method with a parameter that has a custom argument value formatter that throws" .See<IFoo>(foo => foo.Bar(new HasCustomValueFormatterThatThrows())); "And no call is made to the fake" .x(() => { }); "When I assert that the method was called" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(new HasCustomValueFormatterThatThrows())).MustHaveHappened())); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the exception should correctly describe the asserted call, using the next best argument value formatter" .x(() => exception.Message.Should().MatchModuloLineEndings( "*\r\n FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+IFoo.Bar(x: FakeItEasy.Specs.CallDescriptionsInAssertionSpecs+HasCustomValueFormatterThatThrows)\r\n*")); } public class HasCustomValueFormatter { } public class HasCustomValueFormatterValueFormatter : ArgumentValueFormatter<HasCustomValueFormatter> { protected override string GetStringValue(HasCustomValueFormatter argumentValue) { return "hello world"; } } public class HasCustomValueFormatterThatReturnsNull : HasCustomValueFormatter { } public class HasCustomValueFormatterThatReturnsNullValueFormatter : ArgumentValueFormatter<HasCustomValueFormatterThatReturnsNull> { protected override string GetStringValue(HasCustomValueFormatterThatReturnsNull argumentValue) => null!; } public class HasCustomValueFormatterThatThrows { } public class HasCustomValueFormatterThatThrowsValueFormatter : ArgumentValueFormatter<HasCustomValueFormatterThatThrows> { protected override string GetStringValue(HasCustomValueFormatterThatThrows argumentValue) => throw new Exception("Oops"); } } }
#if UNITY_EDITOR using UnityEngine; using System.Collections; public class InspectorPlusFilerStrings { static string q = "\""; static string Quot(string toQuout) { return q + toQuout + q; } public string header; #region inspectorPlusVar public string inspectorPlusVar = @" public class InspectorPlusVar { public enum LimitType { None, Max, Min, Range }; public enum VectorDrawType { None, Direction, Point, PositionHandle, Scale, Rotation }; public LimitType limitType = LimitType.None; public float min = -0.0f; public float max = -0.0f; public bool progressBar; public int iMin = -0; public int iMax = -0; public bool active = true; public string type; public string name; public string dispName; public VectorDrawType vectorDrawType; public bool relative = false; public bool scale = false; public float space = 0.0f; public bool[] labelEnabled = new bool[4]; public string[] label = new string[4]; public bool[] labelBold = new bool[4]; public bool[] labelItalic = new bool[4]; public int[] labelAlign = new int[4]; public bool[] buttonEnabled = new bool[16]; public string[] buttonText = new string[16]; public string[] buttonCallback = new string[16]; public bool[] buttonCondense = new bool[4]; public int numSpace = 0; public string classType; public Vector3 offset = new Vector3(0.5f, 0.5f); public bool QuaternionHandle; public bool canWrite = true; public string tooltip; public bool hasTooltip = false; public bool toggleStart = false; public int toggleSize = 0; public int toggleLevel = 0; public bool largeTexture; public float textureSize; public string textFieldDefault; public bool textArea; public InspectorPlusVar(LimitType _limitType, float _min, float _max, bool _progressBar, int _iMin, int _iMax, bool _active, string _type, string _name, string _dispName, VectorDrawType _vectorDrawType, bool _relative, bool _scale, float _space, bool[] _labelEnabled, string[] _label, bool[] _labelBold, bool[] _labelItalic, int[] _labelAlign, bool[] _buttonEnabled, string[] _buttonText, string[] _buttonCallback, bool[] buttonCondense, int _numSpace, string _classType, Vector3 _offset, bool _QuaternionHandle, bool _canWrite, string _tooltip, bool _hasTooltip, bool _toggleStart, int _toggleSize, int _toggleLevel, bool _largeTexture, float _textureSize, string _textFieldDefault, bool _textArea) { limitType = _limitType; min = _min; max = _max; progressBar = _progressBar; iMax = _iMax; iMin = _iMin; active = _active; type = _type; name = _name; dispName = _dispName; vectorDrawType = _vectorDrawType; relative = _relative; scale = _scale; space = _space; labelEnabled = _labelEnabled; label = _label; labelBold = _labelBold; labelItalic = _labelItalic; labelAlign = _labelAlign; buttonEnabled = _buttonEnabled; buttonText = _buttonText; buttonCallback = _buttonCallback; numSpace = _numSpace; classType = _classType; offset = _offset; QuaternionHandle = _QuaternionHandle; canWrite = _canWrite; tooltip = _tooltip; hasTooltip = _hasTooltip; toggleStart = _toggleStart; toggleSize = _toggleSize; toggleLevel = _toggleLevel; largeTexture = _largeTexture; textureSize = _textureSize; textFieldDefault = _textFieldDefault; textArea = _textArea; } }"; #endregion #region vars public string vars = @" SerializedObject so; SerializedProperty[] properties; new string name; string dispName; Rect tooltipRect; List<InspectorPlusVar> vars; void RefreshVars(){for (int i = 0; i < vars.Count; i += 1) properties[i] = so.FindProperty (vars[i].name);} void OnEnable () { vars = new List<InspectorPlusVar>(); so = serializedObject;"; #endregion #region onEnable public string onEnable = @" int count = vars.Count; properties = new SerializedProperty[count]; } "; #endregion #region progressBar public string progressBar = @" void ProgressBar (float value, string label) { GUILayout.Space (3.0f); Rect rect = GUILayoutUtility.GetRect (18, 18, " + Quot("TextField") + @"); EditorGUI.ProgressBar (rect, value, label); GUILayout.Space (3.0f); }"; #endregion #region propertyField public string propertyField = @" void PropertyField (SerializedProperty sp, string name) { if (sp.hasChildren) { GUILayout.BeginVertical(); while (true) { if (sp.propertyPath != name && !sp.propertyPath.StartsWith (name + " + Quot(".") + @")) break; EditorGUI.indentLevel = sp.depth; bool child = false; if (sp.depth == 0) child = EditorGUILayout.PropertyField(sp, new GUIContent(dispName)); else child = EditorGUILayout.PropertyField(sp); if (!sp.NextVisible (child)) break; } EditorGUI.indentLevel = 0; GUILayout.EndVertical(); } else EditorGUILayout.PropertyField(sp, new GUIContent(dispName)); }"; #endregion #region arrayGUI public string arrayGUI = @" void ArrayGUI (SerializedProperty sp, string name) { EditorGUIUtility.LookLikeControls (120.0f, 40.0f); GUILayout.Space (4.0f); EditorGUILayout.BeginVertical (" + Quot("box") + @", GUILayout.MaxWidth(Screen.width)); int i = 0; int del = -1; SerializedProperty array = sp.Copy (); SerializedProperty size = null; bool first = true; while (true) { if (sp.propertyPath != name && !sp.propertyPath.StartsWith (name + " + Quot(".") + @")) break; bool child; EditorGUI.indentLevel = sp.depth; if (sp.depth == 1 && !first) { EditorGUILayout.BeginHorizontal (); if (GUILayout.Button (" + Quot("") + ", " + Quot("OL Minus") + @", GUILayout.Width (24.0f))) del = i; child = EditorGUILayout.PropertyField (sp); GUI.enabled = i > 0; if (GUILayout.Button (" + Quot("U") + @", " + Quot("ButtonLeft") + @", GUILayout.Width (24.0f), GUILayout.Height(18.0f))) array.MoveArrayElement (i - 1, i); GUI.enabled = i < array.arraySize - 1; if (GUILayout.Button(" + Quot("D") + @", " + Quot("ButtonRight") + @", GUILayout.Width(24.0f), GUILayout.Height(18.0f))) array.MoveArrayElement (i + 1, i); ++i; GUI.enabled = true; EditorGUILayout.EndHorizontal (); } else if (sp.depth == 1) { first = false; size = sp.Copy (); EditorGUILayout.BeginHorizontal (); if (!size.hasMultipleDifferentValues && GUILayout.Button(" + Quot("") + @", " + Quot("OL Plus") + @", GUILayout.Width(24.0f))) array.arraySize += 1; child = EditorGUILayout.PropertyField (sp); EditorGUILayout.EndHorizontal (); } else { child = EditorGUILayout.PropertyField(sp); } if (!sp.NextVisible (child)) break; } sp.Reset (); if (del != -1) array.DeleteArrayElementAtIndex (del); if (array.isExpanded && !size.hasMultipleDifferentValues) { EditorGUILayout.BeginHorizontal (); if (GUILayout.Button(" + Quot("") + @", " + Quot("OL Plus") + @", GUILayout.Width(24.0f))) array.arraySize += 1; GUI.enabled = false; EditorGUILayout.PropertyField (array.GetArrayElementAtIndex (array.arraySize - 1), new GUIContent (" + Quot("") + @" + array.arraySize)); GUI.enabled = true; EditorGUILayout.EndHorizontal (); } EditorGUI.indentLevel = 0; EditorGUILayout.EndVertical (); EditorGUIUtility.LookLikeControls (170.0f, 80.0f); }"; #endregion #region vector2Field public string vector2Field = @" void Vector2Field(SerializedProperty sp) { EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck (); var newValue = EditorGUILayout.Vector2Field (dispName, sp.vector2Value); if (EditorGUI.EndChangeCheck ()) sp.vector2Value = newValue; EditorGUI.EndProperty (); }"; #endregion #region floatField public string floatField = @" void FloatField(SerializedProperty sp, InspectorPlusVar v) { if (v.limitType == InspectorPlusVar.LimitType.Min && !sp.hasMultipleDifferentValues) sp.floatValue = Mathf.Max (v.min, sp.floatValue); else if (v.limitType == InspectorPlusVar.LimitType.Max && !sp.hasMultipleDifferentValues) sp.floatValue = Mathf.Min (v.max, sp.floatValue); if (v.limitType == InspectorPlusVar.LimitType.Range) { if (!v.progressBar) EditorGUILayout.Slider (sp, v.min, v.max); else { if (!sp.hasMultipleDifferentValues) { sp.floatValue = Mathf.Clamp (sp.floatValue, v.min, v.max); ProgressBar ((sp.floatValue - v.min) / v.max, dispName); } else ProgressBar ((sp.floatValue - v.min) / v.max, dispName); } } else EditorGUILayout.PropertyField(sp, new GUIContent(dispName)); }"; #endregion #region intField public string intField = @" void IntField(SerializedProperty sp, InspectorPlusVar v) { if (v.limitType == InspectorPlusVar.LimitType.Min && !sp.hasMultipleDifferentValues) sp.intValue = Mathf.Max (v.iMin, sp.intValue); else if (v.limitType == InspectorPlusVar.LimitType.Max && !sp.hasMultipleDifferentValues) sp.intValue = Mathf.Min (v.iMax, sp.intValue); if (v.limitType == InspectorPlusVar.LimitType.Range) { if (!v.progressBar) { EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck (); var newValue = EditorGUI.IntSlider(GUILayoutUtility.GetRect(18.0f, 18.0f), new GUIContent(dispName), sp.intValue, v.iMin, v.iMax); if (EditorGUI.EndChangeCheck ()) sp.intValue = newValue; EditorGUI.EndProperty (); } else { if (!sp.hasMultipleDifferentValues) { sp.intValue = Mathf.Clamp (sp.intValue, v.iMin, v.iMax); ProgressBar ((float)(sp.intValue - v.iMin) / v.iMax, dispName); } else ProgressBar ((float)(sp.intValue - v.iMin) / v.iMax, dispName); } } else EditorGUILayout.PropertyField(sp, new GUIContent(dispName)); }"; #endregion #region quaternionField public string quaternionField = @" void QuaternionField(SerializedProperty sp) { EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck (); SerializedProperty x = sp.FindPropertyRelative (" + Quot("x") + @"); SerializedProperty y = sp.FindPropertyRelative (" + Quot("y") + @"); SerializedProperty z = sp.FindPropertyRelative (" + Quot("z") + @"); SerializedProperty w = sp.FindPropertyRelative (" + Quot("w") + @"); Quaternion q = new Quaternion (x.floatValue, y.floatValue, z.floatValue, w.floatValue); var newValue = EditorGUILayout.Vector3Field (dispName, q.eulerAngles); if (EditorGUI.EndChangeCheck ()) { Quaternion r = Quaternion.Euler (newValue); x.floatValue = r.x; y.floatValue = r.y; z.floatValue = r.z; w.floatValue = r.w; } EditorGUI.EndProperty (); }"; #endregion public string boolField = @" int BoolField(SerializedProperty sp, InspectorPlusVar v) { if (v.toggleStart) { EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck(); var newValue = EditorGUILayout.Toggle(dispName, sp.boolValue); if (EditorGUI.EndChangeCheck()) sp.boolValue = newValue; EditorGUI.EndProperty(); if (!sp.boolValue) return v.toggleSize; } else EditorGUILayout.PropertyField(sp, new GUIContent(dispName)); return 0; }"; public string textureGUI = @" void TextureGUI(SerializedProperty sp, InspectorPlusVar v) { if (!v.largeTexture) PropertyField(sp, name); else { GUILayout.Label(dispName, GUILayout.Width(145.0f)); EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); var newValue = EditorGUILayout.ObjectField(sp.objectReferenceValue, typeof(Texture2D), false, GUILayout.Width(v.textureSize), GUILayout.Height(v.textureSize)); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) sp.objectReferenceValue = newValue; EditorGUI.EndProperty(); } }"; public string textGUI = @" void TextGUI(SerializedProperty sp, InspectorPlusVar v) { if (v.textFieldDefault == " + Quot("") + @") { PropertyField(sp, name); return; } string focusName = " + Quot("_focusTextField") + @"+ v.name; GUI.SetNextControlName(focusName); EditorGUI.BeginProperty(new Rect(0.0f, 0.0f, 0.0f, 0.0f), new GUIContent(), sp); EditorGUI.BeginChangeCheck(); GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel(dispName); string newValue = " + Quot("") + @"; if (!v.textArea) newValue = EditorGUILayout.TextField(" + Quot("") + @", sp.stringValue, GUILayout.Width(Screen.width)); else newValue = EditorGUILayout.TextArea(sp.stringValue, GUILayout.Width(Screen.width)); if (GUI.GetNameOfFocusedControl() != focusName && !sp.hasMultipleDifferentValues && sp.stringValue == " + Quot("") + @") { GUI.color = new Color(0.7f, 0.7f, 0.7f); GUI.Label(GUILayoutUtility.GetLastRect(), v.textFieldDefault); GUI.color = Color.white; } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); if (EditorGUI.EndChangeCheck()) sp.stringValue = newValue; EditorGUI.EndProperty(); }"; public string GetOnGUI(bool hasFloat, bool hasInt, bool hasProgressBar, bool hasArray, bool hasVector2, bool hasQuaternion, bool hasBool, bool hasTooltip, bool hasSpace, bool hasTexture, bool hasText) { string ret = ""; ret += @" public override void OnInspectorGUI () { so.Update (); RefreshVars(); EditorGUIUtility.LookLikeControls (135.0f, 50.0f); for (int i = 0; i < properties.Length; i += 1) { InspectorPlusVar v = vars[i]; if (v.active && properties[i] != null) { SerializedProperty sp = properties [i];"; bool any = hasFloat || hasInt || hasProgressBar || hasArray || hasVector2 || hasQuaternion || hasBool || hasSpace || hasTexture || hasText; if (any) { ret += @"string s = v.type; bool skip = false;"; } ret += @" name = v.name; dispName = v.dispName; GUI.enabled = v.canWrite; GUILayout.BeginHorizontal(); if (v.toggleLevel != 0) GUILayout.Space(v.toggleLevel * 10.0f); "; if (hasVector2) ret += @" if (s == typeof(Vector2).Name){ Vector2Field(sp); skip = true; }"; if (hasFloat) ret += @" if (s == typeof(float).Name){ FloatField(sp, v); skip = true; }"; if (hasInt) ret += @" if (s == typeof(int).Name){ IntField(sp, v); skip = true; }"; if (hasQuaternion) ret += @" if (s == typeof(Quaternion).Name){ QuaternionField(sp); skip = true; }"; if (hasBool) ret += @" if (s == typeof(bool).Name){ i += BoolField(sp, v); skip = true; }"; if (hasTexture) ret += @" if (s == typeof(Texture2D).Name || s == typeof(Texture).Name){ TextureGUI(sp, v); skip = true; }"; if (hasText) ret += @" if (s == typeof(string).Name){ TextGUI(sp, v); skip = true; }"; if (hasArray) ret += @" if (sp.isArray && s != typeof(string).Name){ ArrayGUI(sp, name); skip = true; }"; if (hasVector2 || hasFloat || hasInt || hasQuaternion || hasBool || hasArray) ret += @" if (!skip)"; ret += @" PropertyField(sp, name); GUILayout.EndHorizontal(); GUI.enabled = true;"; if (hasTooltip) ret += @" if (v.hasTooltip) { Rect last = GUILayoutUtility.GetLastRect(); GUI.Label(last, new GUIContent(" + Quot("") + @", v.tooltip)); GUIStyle style = new GUIStyle(); style.fixedWidth = 250.0f; style.wordWrap = true; Vector2 size = new GUIStyle().CalcSize(new GUIContent(GUI.tooltip)); tooltipRect = new Rect(Event.current.mousePosition.x + 4.0f, Event.current.mousePosition.y + 12.0f, 28.0f + size.x, 9.0f + size.y); if (tooltipRect.width > 250.0f) { float delt = (tooltipRect.width - 250.0f); tooltipRect.width -= delt; tooltipRect.height += size.y * Mathf.CeilToInt(delt / 250.0f); } }"; ret += @" }"; if (hasSpace) ret += @" if (v.space == 0.0f) continue; float usedSpace = 0.0f; for (int j = 0; j < v.numSpace; j += 1) { if (v.labelEnabled [j] || v.buttonEnabled [j]) usedSpace += 18.0f; } if (v.space == 0.0f) continue; float space = Mathf.Max (0.0f, (v.space - usedSpace) / 2.0f); GUILayout.Space (space); for (int j = 0; j < v.numSpace; j += 1) { bool buttonLine = false; for (int k = 0; k < 4; k += 1) if (v.buttonEnabled[j * 4 + k]) buttonLine = true; if (!v.labelEnabled[j] && !buttonLine) continue; GUILayout.BeginHorizontal(); if (v.labelEnabled[j]) { GUIStyle boldItalic = new GUIStyle(); boldItalic.margin = new RectOffset(5, 5, 5, 5); if (v.labelAlign[j] == 0) boldItalic.alignment = TextAnchor.MiddleLeft; else if (v.labelAlign[j] == 1) boldItalic.alignment = TextAnchor.MiddleCenter; else if (v.labelAlign[j] == 2) boldItalic.alignment = TextAnchor.MiddleRight; if (v.labelBold[j] && v.labelItalic[j]) boldItalic.fontStyle = FontStyle.BoldAndItalic; else if (v.labelBold[j]) boldItalic.fontStyle = FontStyle.Bold; else if (v.labelItalic[j]) boldItalic.fontStyle = FontStyle.Italic; GUILayout.Label(v.label[j], boldItalic); boldItalic.alignment = TextAnchor.MiddleLeft; } bool alignRight = (v.labelEnabled[j] && buttonLine); if (!alignRight) { GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); } GUILayout.FlexibleSpace(); for (int k = 0; k < 4; k += 1) { if (v.buttonEnabled[j * 4 + k]) { if (!v.buttonCondense[j] && !alignRight) GUILayout.FlexibleSpace(); string style = " + Quot("Button") + @"; if (v.buttonCondense[j]) { bool hasLeft = false; bool hasRight = false; for(int p = k - 1; p >= 0; p -= 1) if (v.buttonEnabled[j * 4 + p]) hasLeft = true; for (int p = k + 1; p < 4; p += 1) if (v.buttonEnabled[j * 4 + p]) hasRight = true; if (!hasLeft && hasRight) style = " + Quot("ButtonLeft") + @"; else if (hasLeft && hasRight) style = " + Quot("ButtonMid") + @"; else if (hasLeft && !hasRight) style = " + Quot("ButtonRight") + @"; else if (!hasLeft && !hasRight) style = " + Quot("Button") + @"; } if (GUILayout.Button(v.buttonText[j * 4 + k], style, GUILayout.MinWidth(60.0f))) { foreach (object t in targets) { MethodInfo m = t.GetType().GetMethod(v.buttonCallback[j * 4 + k], BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic); if (m != null) m.Invoke(target, null); } } if (!v.buttonCondense[j] && !alignRight) GUILayout.FlexibleSpace(); } } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal (); } GUILayout.Space (space);"; ret += @" } so.ApplyModifiedProperties (); "; if (hasTooltip) ret += @" if (!string.IsNullOrEmpty(GUI.tooltip)) { GUI.color = new Color(1.0f, 1.0f, 1.0f, 1.0f); GUI.Box(tooltipRect, new GUIContent()); EditorGUI.HelpBox(tooltipRect, GUI.tooltip, MessageType.Info); Repaint(); } GUI.tooltip = " + Quot("") + ";"; return ret; } public string watermark = @" //NOTE NOTE NOTE: WATERMARK HERE //You are free to remove this //START REMOVE HERE GUILayout.BeginHorizontal(); GUI.color = new Color(1.0f, 1.0f, 1.0f, 0.3f); GUILayout.FlexibleSpace(); GUILayout.Label(" + Quot("Created with") + @"); GUI.color = new Color(1.0f, 1.0f, 1.0f, 0.6f); if (GUILayout.Button(" + Quot("Inspector++") + @")) Application.OpenURL(" + Quot("http://forum.unity3d.com/threads/136727-Inspector-Meh-to-WOW-inspectors") + @"); GUI.color = new Color(1.0f, 1.0f, 1.0f); GUILayout.EndHorizontal(); //END REMOVE HERE }"; public string vectorScene = @" void VectorScene(InspectorPlusVar v, string s, Transform t) { Vector3 val; if (s == typeof(Vector3).Name) val = (Vector3)GetTargetField(name); else val = (Vector3)((Vector2)GetTargetField(name)); Vector3 newVal = Vector3.zero; Vector3 curVal = Vector3.zero; bool setVal = false; bool relative = v.relative; bool scale = v.scale; switch (v.vectorDrawType) { case InspectorPlusVar.VectorDrawType.Direction: curVal = relative ? val:val - t.position; float size = scale ? Mathf.Min(2.0f, Mathf.Sqrt(curVal.magnitude) / 2.0f) : 1.0f; size *= HandleUtility.GetHandleSize(t.position); Handles.ArrowCap (0, t.position, curVal != Vector3.zero ? Quaternion.LookRotation (val.normalized) : Quaternion.identity, size); break; case InspectorPlusVar.VectorDrawType.Point: curVal = relative ? val:t.position + val; Handles.SphereCap (0, curVal, Quaternion.identity, 0.1f); break; case InspectorPlusVar.VectorDrawType.PositionHandle: curVal = relative ? t.position + val:val; setVal = true; newVal = Handles.PositionHandle (curVal, Quaternion.identity) - (relative ? t.position : Vector3.zero); break; case InspectorPlusVar.VectorDrawType.Scale: setVal = true; curVal = relative ? t.localScale + val :val; newVal = Handles.ScaleHandle(curVal, t.position + v.offset, t.rotation, HandleUtility.GetHandleSize(t.position + v.offset)) - (relative ? t.localScale : Vector3.zero); break; case InspectorPlusVar.VectorDrawType.Rotation: setVal = true; curVal = relative ? val + t.rotation.eulerAngles : val; newVal = Handles.RotationHandle(Quaternion.Euler(curVal), t.position + v.offset).eulerAngles - (relative?t.rotation.eulerAngles:Vector3.zero); break; } if (setVal) { object newObjectVal = newVal; if (s==typeof(Vector2).Name) newObjectVal = (Vector2)newVal; else if (s == typeof(Quaternion).Name) newObjectVal = Quaternion.Euler(newVal); SetTargetField(name, newObjectVal); } }"; public string quaternionScene = @" void QuaternionScene(Transform t, Vector3 offset) { Quaternion val = (Quaternion)GetTargetField(name); SetTargetField(name, Handles.RotationHandle (val, t.position + offset)); }"; public string GetSceneString(bool hasScene, bool hasVectorScene, bool hasQuaternionScene) { string ret = ""; ret += @" object GetTargetField(string name){return target.GetType ().GetField (name).GetValue (target);} void SetTargetField(string name, object value){target.GetType ().GetField (name).SetValue (target, value);} //some magic to draw the handles public void OnSceneGUI () { Transform t = ((MonoBehaviour)target).transform; foreach (InspectorPlusVar v in vars) { if (!v.active) continue; string s = v.type; name = v.name;"; if (hasVectorScene) ret += @" if (s == typeof(Vector3).Name || s == typeof(Vector2).Name) VectorScene(v, s, t);"; if (hasQuaternionScene) ret += @" if (s == typeof(Quaternion).Name && v.QuaternionHandle) QuaternionScene(t, v.offset);"; ret += @" } }"; return ret; } public InspectorPlusFilerStrings(string name, string fileName, bool hasInspector) { header = @" using UnityEngine; using System.Collections.Generic; using UnityEditor; using System.Reflection; using System; using Object = UnityEngine.Object;"; if (hasInspector) header += @" using InspectorPlusVar = " + fileName + @".InspectorPlusVar;"; header += @" [CanEditMultipleObjects] [CustomEditor(typeof(" + name + @"))] public class " + fileName + @" : Editor {"; } } #endif
#region Copyright notice and license // Copyright 2015-2016 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Google.Protobuf; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Testing; using NUnit.Framework; namespace Grpc.IntegrationTesting { /// <summary> /// Test SSL credentials where server authenticates client /// and client authenticates the server. /// </summary> public class SslCredentialsTest { const string Host = "localhost"; const string IsPeerAuthenticatedMetadataKey = "test_only_is_peer_authenticated"; Server server; Channel channel; TestService.TestServiceClient client; string rootCert; KeyCertificatePair keyCertPair; public void InitClientAndServer(bool clientAddKeyCertPair, SslClientCertificateRequestType clientCertRequestType, VerifyPeerCallback verifyPeerCallback = null) { rootCert = File.ReadAllText(TestCredentials.ClientCertAuthorityPath); keyCertPair = new KeyCertificatePair( File.ReadAllText(TestCredentials.ServerCertChainPath), File.ReadAllText(TestCredentials.ServerPrivateKeyPath)); var serverCredentials = new SslServerCredentials(new[] { keyCertPair }, rootCert, clientCertRequestType); var clientCredentials = new SslCredentials(rootCert, clientAddKeyCertPair ? keyCertPair : null, verifyPeerCallback); // Disable SO_REUSEPORT to prevent https://github.com/grpc/grpc/issues/10755 server = new Server(new[] { new ChannelOption(ChannelOptions.SoReuseport, 0) }) { Services = { TestService.BindService(new SslCredentialsTestServiceImpl()) }, Ports = { { Host, ServerPort.PickUnused, serverCredentials } } }; server.Start(); var options = new List<ChannelOption> { new ChannelOption(ChannelOptions.SslTargetNameOverride, TestCredentials.DefaultHostOverride) }; channel = new Channel(Host, server.Ports.Single().BoundPort, clientCredentials, options); client = new TestService.TestServiceClient(channel); } [OneTimeTearDown] public void Cleanup() { if (channel != null) { channel.ShutdownAsync().Wait(); } if (server != null) { server.ShutdownAsync().Wait(); } } [Test] public async Task NoClientCert_DontRequestClientCertificate_Accepted() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.DontRequest); await CheckAccepted(expectPeerAuthenticated: false); } [Test] public async Task ClientWithCert_DontRequestClientCertificate_AcceptedButPeerNotAuthenticated() { InitClientAndServer( clientAddKeyCertPair: true, clientCertRequestType: SslClientCertificateRequestType.DontRequest); await CheckAccepted(expectPeerAuthenticated: false); } [Test] public async Task NoClientCert_RequestClientCertificateButDontVerify_Accepted() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.RequestButDontVerify); await CheckAccepted(expectPeerAuthenticated: false); } [Test] public async Task NoClientCert_RequestClientCertificateAndVerify_Accepted() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.RequestAndVerify); await CheckAccepted(expectPeerAuthenticated: false); } [Test] public async Task ClientWithCert_RequestAndRequireClientCertificateButDontVerify_Accepted() { InitClientAndServer( clientAddKeyCertPair: true, clientCertRequestType: SslClientCertificateRequestType.RequestAndRequireButDontVerify); await CheckAccepted(expectPeerAuthenticated: true); await CheckAuthContextIsPopulated(); } [Test] public async Task ClientWithCert_RequestAndRequireClientCertificateAndVerify_Accepted() { InitClientAndServer( clientAddKeyCertPair: true, clientCertRequestType: SslClientCertificateRequestType.RequestAndRequireAndVerify); await CheckAccepted(expectPeerAuthenticated: true); await CheckAuthContextIsPopulated(); } [Test] public void NoClientCert_RequestAndRequireClientCertificateButDontVerify_Rejected() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.RequestAndRequireButDontVerify); CheckRejected(); } [Test] public void NoClientCert_RequestAndRequireClientCertificateAndVerify_Rejected() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.RequestAndRequireAndVerify); CheckRejected(); } [Test] public void Constructor_LegacyForceClientAuth() { var creds = new SslServerCredentials(new[] { keyCertPair }, rootCert, true); Assert.AreEqual(SslClientCertificateRequestType.RequestAndRequireAndVerify, creds.ClientCertificateRequest); var creds2 = new SslServerCredentials(new[] { keyCertPair }, rootCert, false); Assert.AreEqual(SslClientCertificateRequestType.DontRequest, creds2.ClientCertificateRequest); } [Test] public void Constructor_NullRootCerts() { var keyCertPairs = new[] { keyCertPair }; Assert.DoesNotThrow(() => new SslServerCredentials(keyCertPairs, null, SslClientCertificateRequestType.DontRequest)); Assert.DoesNotThrow(() => new SslServerCredentials(keyCertPairs, null, SslClientCertificateRequestType.RequestAndVerify)); Assert.DoesNotThrow(() => new SslServerCredentials(keyCertPairs, null, SslClientCertificateRequestType.RequestAndRequireButDontVerify)); Assert.Throws(typeof(ArgumentNullException), () => new SslServerCredentials(keyCertPairs, null, SslClientCertificateRequestType.RequestAndRequireAndVerify)); } [Test] public async Task VerifyPeerCallback_Accepted() { string targetNameFromCallback = null; string peerPemFromCallback = null; InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.DontRequest, verifyPeerCallback: (ctx) => { targetNameFromCallback = ctx.TargetName; peerPemFromCallback = ctx.PeerPem; return true; }); await CheckAccepted(expectPeerAuthenticated: false); Assert.AreEqual(TestCredentials.DefaultHostOverride, targetNameFromCallback); var expectedServerPem = File.ReadAllText(TestCredentials.ServerCertChainPath).Replace("\r", ""); Assert.AreEqual(expectedServerPem, peerPemFromCallback); } [Test] public void VerifyPeerCallback_CallbackThrows_Rejected() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.DontRequest, verifyPeerCallback: (ctx) => { throw new Exception("VerifyPeerCallback has thrown on purpose."); }); CheckRejected(); } [Test] public void VerifyPeerCallback_Rejected() { InitClientAndServer( clientAddKeyCertPair: false, clientCertRequestType: SslClientCertificateRequestType.DontRequest, verifyPeerCallback: (ctx) => { return false; }); CheckRejected(); } private async Task CheckAccepted(bool expectPeerAuthenticated) { var call = client.UnaryCallAsync(new SimpleRequest { ResponseSize = 10 }); var response = await call; Assert.AreEqual(10, response.Payload.Body.Length); Assert.AreEqual(expectPeerAuthenticated.ToString(), call.GetTrailers().First((entry) => entry.Key == IsPeerAuthenticatedMetadataKey).Value); } private void CheckRejected() { var ex = Assert.Throws<RpcException>(() => client.UnaryCall(new SimpleRequest { ResponseSize = 10 })); Assert.AreEqual(StatusCode.Unavailable, ex.Status.StatusCode); } private async Task CheckAuthContextIsPopulated() { var call = client.StreamingInputCall(); await call.RequestStream.CompleteAsync(); var response = await call.ResponseAsync; Assert.AreEqual(12345, response.AggregatedPayloadSize); } private class SslCredentialsTestServiceImpl : TestService.TestServiceBase { public override Task<SimpleResponse> UnaryCall(SimpleRequest request, ServerCallContext context) { context.ResponseTrailers.Add(IsPeerAuthenticatedMetadataKey, context.AuthContext.IsPeerAuthenticated.ToString()); return Task.FromResult(new SimpleResponse { Payload = CreateZerosPayload(request.ResponseSize) }); } public override async Task<StreamingInputCallResponse> StreamingInputCall(IAsyncStreamReader<StreamingInputCallRequest> requestStream, ServerCallContext context) { var authContext = context.AuthContext; await requestStream.ForEachAsync(request => TaskUtils.CompletedTask); Assert.IsTrue(authContext.IsPeerAuthenticated); Assert.AreEqual("x509_subject_alternative_name", authContext.PeerIdentityPropertyName); Assert.IsTrue(authContext.PeerIdentity.Count() > 0); Assert.AreEqual("ssl", authContext.FindPropertiesByName("transport_security_type").First().Value); return new StreamingInputCallResponse { AggregatedPayloadSize = 12345 }; } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: List for exceptions. ** ** ===========================================================*/ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary using a singly linked list. This /// will be smaller and faster than a Hashtable if the number of elements is 10 or less. /// This should not be used if performance is important for large numbers of elements. [Serializable] internal class ListDictionaryInternal: IDictionary { DictionaryNode head; int version; int count; [NonSerialized] private Object _syncRoot; public ListDictionaryInternal() { } public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); DictionaryNode node = head; while (node != null) { if ( node.key.Equals(key) ) { return node.value; } node = node.next; } return null; } set { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key"); if( (value != null) && (!value.GetType().IsSerializable ) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value"); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if( node.key.Equals(key) ) { break; } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } } public int Count { get { return count; } } public ICollection Keys { get { return new NodeKeyValueCollection(this, true); } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public bool IsSynchronized { get { return false; } } public Object SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } public ICollection Values { get { return new NodeKeyValueCollection(this, false); } } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "key" ); if( (value != null) && (!value.GetType().IsSerializable) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), "value"); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", node.key, key)); } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } public void Clear() { count = 0; head = null; version++; } public bool Contains(Object key) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { if (node.key.Equals(key)) { return true; } } return false; } public void CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( array.Length - index < this.Count ) throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), "index"); Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(Object key) { if (key == null) { throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { break; } last = node; } if (node == null) { return; } if (node == head) { head = node.next; } else { last.next = node.next; } count--; } private class NodeEnumerator : IDictionaryEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool start; public NodeEnumerator(ListDictionaryInternal list) { this.list = list; version = list.version; start = true; current = null; } public Object Current { get { return Entry; } } public DictionaryEntry Entry { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return new DictionaryEntry(current.key, current.value); } } public Object Key { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.key; } } public Object Value { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null ) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } private class NodeKeyValueCollection : ICollection { ListDictionaryInternal list; bool isKeys; public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (array.Length - index < list.Count) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), "index"); for (DictionaryNode node = list.head; node != null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; } } int ICollection.Count { get { int count = 0; for (DictionaryNode node = list.head; node != null; node = node.next) { count++; } return count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return list.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(list, isKeys); } private class NodeKeyValueEnumerator: IEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool isKeys; bool start; public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; this.version = list.version; this.start = true; this.current = null; } public Object Current { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return isKeys ? current.key : current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } } [Serializable] private class DictionaryNode { public Object key; public Object value; public DictionaryNode next; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Globalization; using System.Text; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections; using System.Diagnostics; using System.Reflection; namespace System.Management.Automation.Help { /// <summary> /// Positional parameter comparer /// </summary> internal class PositionalParameterComparer : IComparer { /// <summary> /// /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public int Compare(object x, object y) { CommandParameterInfo a = x as CommandParameterInfo; CommandParameterInfo b = y as CommandParameterInfo; Debug.Assert(a != null && b != null); return (a.Position - b.Position); } } /// <summary> /// The help object builder class attempts to create a full HelpInfo object from /// a CmdletInfo object. This is used to generate the default UX when no help content /// is present in the box. This class mimics the exact same structure as that of a MAML /// node, so that the default UX does not introduce regressions. /// </summary> internal class DefaultCommandHelpObjectBuilder { internal static string TypeNameForDefaultHelp = "ExtendedCmdletHelpInfo"; /// <summary> /// Generates a HelpInfo PSObject from a CmdletInfo object /// </summary> /// <param name="input">command info</param> /// <returns>HelpInfo PSObject</returns> internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input) { // Create a copy of commandInfo for GetCommandCommand so that we can generate parameter // sets based on Dynamic Parameters (+ optional arguments) CommandInfo commandInfo = input.CreateGetCommandCopy(null); PSObject obj = new PSObject(); obj.TypeNames.Clear(); obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); obj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp); obj.TypeNames.Add("CmdletHelpInfo"); obj.TypeNames.Add("HelpInfo"); if (commandInfo is CmdletInfo) { CmdletInfo cmdletInfo = commandInfo as CmdletInfo; bool common = false; bool commonWorkflow = false; if (cmdletInfo.Parameters != null) { common = HasCommonParameters(cmdletInfo.Parameters); commonWorkflow = ((cmdletInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow); } obj.Properties.Add(new PSNoteProperty("CommonParameters", common)); obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow)); AddDetailsProperties(obj, cmdletInfo.Name, cmdletInfo.Noun, cmdletInfo.Verb, TypeNameForDefaultHelp); AddSyntaxProperties(obj, cmdletInfo.Name, cmdletInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp); AddParametersProperties(obj, cmdletInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp); AddInputTypesProperties(obj, cmdletInfo.Parameters); AddRelatedLinksProperties(obj, commandInfo.CommandMetadata.HelpUri); try { AddOutputTypesProperties(obj, cmdletInfo.OutputType); } catch (PSInvalidOperationException) { AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>())); } AddAliasesProperties(obj, cmdletInfo.Name, cmdletInfo.Context); if (HasHelpInfoUri(cmdletInfo.Module, cmdletInfo.ModuleName)) { AddRemarksProperties(obj, cmdletInfo.Name, cmdletInfo.CommandMetadata.HelpUri); } else { obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None)); } obj.Properties.Add(new PSNoteProperty("PSSnapIn", cmdletInfo.PSSnapIn)); } else if (commandInfo is FunctionInfo) { FunctionInfo funcInfo = commandInfo as FunctionInfo; bool common = HasCommonParameters(funcInfo.Parameters); bool commonWorkflow = ((commandInfo.CommandType & CommandTypes.Workflow) == CommandTypes.Workflow); obj.Properties.Add(new PSNoteProperty("CommonParameters", common)); obj.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow)); AddDetailsProperties(obj, funcInfo.Name, String.Empty, String.Empty, TypeNameForDefaultHelp); AddSyntaxProperties(obj, funcInfo.Name, funcInfo.ParameterSets, common, commonWorkflow, TypeNameForDefaultHelp); AddParametersProperties(obj, funcInfo.Parameters, common, commonWorkflow, TypeNameForDefaultHelp); AddInputTypesProperties(obj, funcInfo.Parameters); AddRelatedLinksProperties(obj, funcInfo.CommandMetadata.HelpUri); try { AddOutputTypesProperties(obj, funcInfo.OutputType); } catch (PSInvalidOperationException) { AddOutputTypesProperties(obj, new ReadOnlyCollection<PSTypeName>(new List<PSTypeName>())); } AddAliasesProperties(obj, funcInfo.Name, funcInfo.Context); if (HasHelpInfoUri(funcInfo.Module, funcInfo.ModuleName)) { AddRemarksProperties(obj, funcInfo.Name, funcInfo.CommandMetadata.HelpUri); } else { obj.Properties.Add(new PSNoteProperty("remarks", HelpDisplayStrings.None)); } } obj.Properties.Add(new PSNoteProperty("alertSet", null)); obj.Properties.Add(new PSNoteProperty("description", null)); obj.Properties.Add(new PSNoteProperty("examples", null)); obj.Properties.Add(new PSNoteProperty("Synopsis", commandInfo.Syntax)); obj.Properties.Add(new PSNoteProperty("ModuleName", commandInfo.ModuleName)); obj.Properties.Add(new PSNoteProperty("nonTerminatingErrors", String.Empty)); obj.Properties.Add(new PSNoteProperty("xmlns:command", "http://schemas.microsoft.com/maml/dev/command/2004/10")); obj.Properties.Add(new PSNoteProperty("xmlns:dev", "http://schemas.microsoft.com/maml/dev/2004/10")); obj.Properties.Add(new PSNoteProperty("xmlns:maml", "http://schemas.microsoft.com/maml/2004/10")); return obj; } /// <summary> /// Adds the details properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="name">command name</param> /// <param name="noun">command noun</param> /// <param name="verb">command verb</param> /// <param name="typeNameForHelp">type name for help</param> /// <param name="synopsis">synopsis</param> internal static void AddDetailsProperties(PSObject obj, string name, string noun, string verb, string typeNameForHelp, string synopsis = null) { PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp)); mshObject.Properties.Add(new PSNoteProperty("name", name)); mshObject.Properties.Add(new PSNoteProperty("noun", noun)); mshObject.Properties.Add(new PSNoteProperty("verb", verb)); // add synopsis if (!string.IsNullOrEmpty(synopsis)) { PSObject descriptionObject = new PSObject(); descriptionObject.TypeNames.Clear(); descriptionObject.TypeNames.Add("MamlParaTextItem"); descriptionObject.Properties.Add(new PSNoteProperty("Text", synopsis)); mshObject.Properties.Add(new PSNoteProperty("Description", descriptionObject)); } obj.Properties.Add(new PSNoteProperty("details", mshObject)); } /// <summary> /// Adds the syntax properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="cmdletName">command name</param> /// <param name="parameterSets">parameter sets</param> /// <param name="common">common parameters</param> /// <param name="commonWorkflow">common workflow parameters</param> /// <param name="typeNameForHelp">type name for help</param> internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp) { PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp)); AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, commonWorkflow, typeNameForHelp); obj.Properties.Add(new PSNoteProperty("Syntax", mshObject)); } /// <summary> /// Add the syntax item properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="cmdletName">cmdlet name, you can't get this from parameterSets</param> /// <param name="parameterSets">a collection of parameter sets</param> /// <param name="common">common parameters</param> /// <param name="commonWorkflow">common workflow parameters</param> /// <param name="typeNameForHelp">type name for help</param> private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, ReadOnlyCollection<CommandParameterSetInfo> parameterSets, bool common, bool commonWorkflow, string typeNameForHelp) { ArrayList mshObjects = new ArrayList(); foreach (CommandParameterSetInfo parameterSet in parameterSets) { PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp)); mshObject.Properties.Add(new PSNoteProperty("name", cmdletName)); mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common)); mshObject.Properties.Add(new PSNoteProperty("WorkflowCommonParameters", commonWorkflow)); Collection<CommandParameterInfo> parameters = new Collection<CommandParameterInfo>(); // GenerateParameters parameters in display order // ie., Postional followed by // Named Mandatory (in alpha numeric) followed by // Named (in alpha numeric) parameterSet.GenerateParametersInDisplayOrder(commonWorkflow, parameters.Add, delegate { }); AddSyntaxParametersProperties(mshObject, parameters, common, commonWorkflow, parameterSet.Name); mshObjects.Add(mshObject); } obj.Properties.Add(new PSNoteProperty("syntaxItem", mshObjects.ToArray())); } /// <summary> /// Add the syntax parameters properties (these parameters are used to create the syntax section) /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="parameters"> /// a collection of parameters in display order /// ie., Postional followed by /// Named Mandatory (in alpha numeric) followed by /// Named (in alpha numeric) /// </param> /// <param name="common">common parameters</param> /// <param name="commonWorkflow">common workflow</param> /// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param> private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable<CommandParameterInfo> parameters, bool common, bool commonWorkflow, string parameterSetName) { ArrayList mshObjects = new ArrayList(); foreach (CommandParameterInfo parameter in parameters) { if (commonWorkflow && IsCommonWorkflowParameter(parameter.Name)) { continue; } if (common && Cmdlet.CommonParameters.Contains(parameter.Name)) { continue; } PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); Collection<Attribute> attributes = new Collection<Attribute>(parameter.Attributes); AddParameterProperties(mshObject, parameter.Name, new Collection<string>(parameter.Aliases), parameter.IsDynamic, parameter.ParameterType, attributes, parameterSetName); Collection<ValidateSetAttribute> validateSet = GetValidateSetAttribute(attributes); List<string> names = new List<string>(); foreach (ValidateSetAttribute set in validateSet) { foreach (string value in set.ValidValues) { names.Add(value); } } if (names.Count != 0) { AddParameterValueGroupProperties(mshObject, names.ToArray()); } else { if (parameter.ParameterType.GetTypeInfo().IsEnum && (Enum.GetNames(parameter.ParameterType) != null)) { AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType)); } else if (parameter.ParameterType.IsArray) { if (parameter.ParameterType.GetElementType().GetTypeInfo().IsEnum && Enum.GetNames(parameter.ParameterType.GetElementType()) != null) { AddParameterValueGroupProperties(mshObject, Enum.GetNames(parameter.ParameterType.GetElementType())); } } else if (parameter.ParameterType.GetTypeInfo().IsGenericType) { Type[] types = parameter.ParameterType.GetGenericArguments(); if (types.Length != 0) { Type type = types[0]; if (type.GetTypeInfo().IsEnum && (Enum.GetNames(type) != null)) { AddParameterValueGroupProperties(mshObject, Enum.GetNames(type)); } else if (type.IsArray) { if (type.GetElementType().GetTypeInfo().IsEnum && Enum.GetNames(type.GetElementType()) != null) { AddParameterValueGroupProperties(mshObject, Enum.GetNames(type.GetElementType())); } } } } } mshObjects.Add(mshObject); } obj.Properties.Add(new PSNoteProperty("parameter", mshObjects.ToArray())); } /// <summary> /// Adds a parameter value group (for enums) /// </summary> /// <param name="obj">object</param> /// <param name="values">parameter group values</param> private static void AddParameterValueGroupProperties(PSObject obj, string[] values) { PSObject paramValueGroup = new PSObject(); paramValueGroup.TypeNames.Clear(); paramValueGroup.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); ArrayList paramValue = new ArrayList(values); paramValueGroup.Properties.Add(new PSNoteProperty("parameterValue", paramValue.ToArray())); obj.Properties.Add(new PSNoteProperty("parameterValueGroup", paramValueGroup)); } /// <summary> /// Add the parameters properties (these parameters are used to create the parameters section) /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="parameters">parameters</param> /// <param name="common">common parameters</param> /// <param name="commonWorkflow">common workflow parameters</param> /// <param name="typeNameForHelp">type name for help</param> internal static void AddParametersProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters, bool common, bool commonWorkflow, string typeNameForHelp) { PSObject paramsObject = new PSObject(); paramsObject.TypeNames.Clear(); paramsObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameters", typeNameForHelp)); ArrayList paramObjects = new ArrayList(); ArrayList sortedParameters = new ArrayList(); if (parameters != null) { foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters) { sortedParameters.Add(parameter.Key); } } sortedParameters.Sort(StringComparer.Ordinal); foreach (string parameter in sortedParameters) { if (commonWorkflow && IsCommonWorkflowParameter(parameter)) { continue; } if (common && Cmdlet.CommonParameters.Contains(parameter)) { continue; } PSObject paramObject = new PSObject(); paramObject.TypeNames.Clear(); paramObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#parameter", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); AddParameterProperties(paramObject, parameter, parameters[parameter].Aliases, parameters[parameter].IsDynamic, parameters[parameter].ParameterType, parameters[parameter].Attributes); paramObjects.Add(paramObject); } paramsObject.Properties.Add(new PSNoteProperty("parameter", paramObjects.ToArray())); obj.Properties.Add(new PSNoteProperty("parameters", paramsObject)); } /// <summary> /// Adds the parameter properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="name">parameter name</param> /// <param name="aliases">parameter aliases</param> /// <param name="dynamic">is dynamic parameter?</param> /// <param name="type">parameter type</param> /// <param name="attributes">parameter attributes</param> /// <param name="parameterSetName">Name of the parameter set for which the syntax is generated</param> private static void AddParameterProperties(PSObject obj, string name, Collection<string> aliases, bool dynamic, Type type, Collection<Attribute> attributes, string parameterSetName = null) { Collection<ParameterAttribute> attribs = GetParameterAttribute(attributes); obj.Properties.Add(new PSNoteProperty("name", name)); if (attribs.Count == 0) { obj.Properties.Add(new PSNoteProperty("required", "")); obj.Properties.Add(new PSNoteProperty("pipelineInput", "")); obj.Properties.Add(new PSNoteProperty("isDynamic", "")); obj.Properties.Add(new PSNoteProperty("parameterSetName", "")); obj.Properties.Add(new PSNoteProperty("description", "")); obj.Properties.Add(new PSNoteProperty("position", "")); obj.Properties.Add(new PSNoteProperty("aliases", "")); } else { ParameterAttribute paramAttribute = attribs[0]; if (!string.IsNullOrEmpty(parameterSetName)) { foreach (var attrib in attribs) { if (string.Equals(attrib.ParameterSetName, parameterSetName, StringComparison.OrdinalIgnoreCase)) { paramAttribute = attrib; break; } } } obj.Properties.Add(new PSNoteProperty("required", CultureInfo.CurrentCulture.TextInfo.ToLower(paramAttribute.Mandatory.ToString()))); obj.Properties.Add(new PSNoteProperty("pipelineInput", GetPipelineInputString(paramAttribute))); obj.Properties.Add(new PSNoteProperty("isDynamic", CultureInfo.CurrentCulture.TextInfo.ToLower(dynamic.ToString()))); if (paramAttribute.ParameterSetName.Equals(ParameterAttribute.AllParameterSets, StringComparison.OrdinalIgnoreCase)) { obj.Properties.Add(new PSNoteProperty("parameterSetName", StringUtil.Format(HelpDisplayStrings.AllParameterSetsName))); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < attribs.Count; i++) { sb.Append(attribs[i].ParameterSetName); if (i != (attribs.Count - 1)) { sb.Append(", "); } } obj.Properties.Add(new PSNoteProperty("parameterSetName", sb.ToString())); } if (paramAttribute.HelpMessage != null) { StringBuilder sb = new StringBuilder(); sb.AppendLine(paramAttribute.HelpMessage); obj.Properties.Add(new PSNoteProperty("description", sb.ToString())); } // We do not show switch parameters in the syntax section // (i.e. [-Syntax] not [-Syntax <SwitchParameter>] if (type != typeof(SwitchParameter)) { AddParameterValueProperties(obj, type, attributes); } AddParameterTypeProperties(obj, type, attributes); if (paramAttribute.Position == int.MinValue) { obj.Properties.Add(new PSNoteProperty("position", StringUtil.Format(HelpDisplayStrings.NamedParameter))); } else { obj.Properties.Add(new PSNoteProperty("position", paramAttribute.Position.ToString(CultureInfo.InvariantCulture))); } if (aliases.Count == 0) { obj.Properties.Add(new PSNoteProperty("aliases", StringUtil.Format( HelpDisplayStrings.None))); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < aliases.Count; i++) { sb.Append(aliases[i]); if (i != (aliases.Count - 1)) { sb.Append(", "); } } obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString())); } } } /// <summary> /// Adds the parameterType properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="parameterType">the type of a parameter</param> /// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param> private static void AddParameterTypeProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes) { PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); mshObject.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes); mshObject.Properties.Add(new PSNoteProperty("name", parameterTypeString)); obj.Properties.Add(new PSNoteProperty("type", mshObject)); } /// <summary> /// Adds the parameterValue properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="parameterType">the type of a parameter</param> /// <param name="attributes">the attributes of the parameter (needed to look for PSTypeName)</param> private static void AddParameterValueProperties(PSObject obj, Type parameterType, IEnumerable<Attribute> attributes) { PSObject mshObject; if (parameterType != null) { Type type = Nullable.GetUnderlyingType(parameterType) ?? parameterType; var parameterTypeString = CommandParameterSetInfo.GetParameterTypeString(parameterType, attributes); mshObject = new PSObject(parameterTypeString); mshObject.Properties.Add(new PSNoteProperty("variableLength", parameterType.IsArray)); } else { mshObject = new PSObject("System.Object"); mshObject.Properties.Add(new PSNoteProperty("variableLength", StringUtil.Format(HelpDisplayStrings.FalseShort))); } mshObject.Properties.Add(new PSNoteProperty("required", "true")); obj.Properties.Add(new PSNoteProperty("parameterValue", mshObject)); } /// <summary> /// Adds the InputTypes properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="parameters">command parameters</param> internal static void AddInputTypesProperties(PSObject obj, Dictionary<string, ParameterMetadata> parameters) { Collection<string> inputs = new Collection<string>(); if (parameters != null) { foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters) { Collection<ParameterAttribute> attribs = GetParameterAttribute(parameter.Value.Attributes); foreach (ParameterAttribute attrib in attribs) { if (attrib.ValueFromPipeline || attrib.ValueFromPipelineByPropertyName || attrib.ValueFromRemainingArguments) { if (!inputs.Contains(parameter.Value.ParameterType.FullName)) { inputs.Add(parameter.Value.ParameterType.FullName); } } } } } if (inputs.Count == 0) { inputs.Add(StringUtil.Format(HelpDisplayStrings.None)); } StringBuilder sb = new StringBuilder(); foreach (string input in inputs) { sb.AppendLine(input); } PSObject inputTypesObj = new PSObject(); inputTypesObj.TypeNames.Clear(); inputTypesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputTypes", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject inputTypeObj = new PSObject(); inputTypeObj.TypeNames.Clear(); inputTypeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#inputType", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject typeObj = new PSObject(); typeObj.TypeNames.Clear(); typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString())); inputTypeObj.Properties.Add(new PSNoteProperty("type", typeObj)); inputTypesObj.Properties.Add(new PSNoteProperty("inputType", inputTypeObj)); obj.Properties.Add(new PSNoteProperty("inputTypes", inputTypesObj)); } /// <summary> /// Adds the OutputTypes properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="outputTypes">output types</param> private static void AddOutputTypesProperties(PSObject obj, ReadOnlyCollection<PSTypeName> outputTypes) { PSObject returnValuesObj = new PSObject(); returnValuesObj.TypeNames.Clear(); returnValuesObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValues", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject returnValueObj = new PSObject(); returnValueObj.TypeNames.Clear(); returnValueObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#returnValue", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); PSObject typeObj = new PSObject(); typeObj.TypeNames.Clear(); typeObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#type", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); if (outputTypes.Count == 0) { typeObj.Properties.Add(new PSNoteProperty("name", "System.Object")); } else { StringBuilder sb = new StringBuilder(); foreach (PSTypeName outputType in outputTypes) { sb.AppendLine(outputType.Name); } typeObj.Properties.Add(new PSNoteProperty("name", sb.ToString())); } returnValueObj.Properties.Add(new PSNoteProperty("type", typeObj)); returnValuesObj.Properties.Add(new PSNoteProperty("returnValue", returnValueObj)); obj.Properties.Add(new PSNoteProperty("returnValues", returnValuesObj)); } /// <summary> /// Adds the aliases properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="name">command name</param> /// <param name="context">execution context</param> private static void AddAliasesProperties(PSObject obj, string name, ExecutionContext context) { StringBuilder sb = new StringBuilder(); bool found = false; if (context != null) { foreach (string alias in context.SessionState.Internal.GetAliasesByCommandName(name)) { found = true; sb.AppendLine(alias); } } if (!found) { sb.AppendLine(StringUtil.Format(HelpDisplayStrings.None)); } obj.Properties.Add(new PSNoteProperty("aliases", sb.ToString())); } /// <summary> /// Adds the remarks properties /// </summary> /// <param name="obj">HelpInfo object</param> /// <param name="cmdletName"></param> /// <param name="helpUri"></param> private static void AddRemarksProperties(PSObject obj, string cmdletName, string helpUri) { if (String.IsNullOrEmpty(helpUri)) { obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContentWithoutHelpUri, cmdletName))); } else { obj.Properties.Add(new PSNoteProperty("remarks", StringUtil.Format(HelpDisplayStrings.GetLatestHelpContent, cmdletName, helpUri))); } } /// <summary> /// Adds the related links properties /// </summary> /// <param name="obj"></param> /// <param name="relatedLink"></param> internal static void AddRelatedLinksProperties(PSObject obj, string relatedLink) { if (!String.IsNullOrEmpty(relatedLink)) { PSObject navigationLinkObj = new PSObject(); navigationLinkObj.TypeNames.Clear(); navigationLinkObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#navigationLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); navigationLinkObj.Properties.Add(new PSNoteProperty("uri", relatedLink)); List<PSObject> navigationLinkValues = new List<PSObject> { navigationLinkObj }; // check if obj already has relatedLinks property PSNoteProperty relatedLinksPO = obj.Properties["relatedLinks"] as PSNoteProperty; if ((relatedLinksPO != null) && (relatedLinksPO.Value != null)) { PSObject relatedLinksValue = PSObject.AsPSObject(relatedLinksPO.Value); PSNoteProperty navigationLinkPO = relatedLinksValue.Properties["navigationLink"] as PSNoteProperty; if ((navigationLinkPO != null) && (navigationLinkPO.Value != null)) { PSObject navigationLinkValue = navigationLinkPO.Value as PSObject; if (navigationLinkValue != null) { navigationLinkValues.Add(navigationLinkValue); } else { PSObject[] navigationLinkValueArray = navigationLinkPO.Value as PSObject[]; if (navigationLinkValueArray != null) { foreach (var psObject in navigationLinkValueArray) { navigationLinkValues.Add(psObject); } } } } } PSObject relatedLinksObj = new PSObject(); relatedLinksObj.TypeNames.Clear(); relatedLinksObj.TypeNames.Add(String.Format(CultureInfo.InvariantCulture, "{0}#relatedLinks", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); relatedLinksObj.Properties.Add(new PSNoteProperty("navigationLink", navigationLinkValues.ToArray())); obj.Properties.Add(new PSNoteProperty("relatedLinks", relatedLinksObj)); } } /// <summary> /// Gets the parameter attribute from parameter metadata /// </summary> /// <param name="attributes">parameter attributes</param> /// <returns>parameter attributes</returns> private static Collection<ParameterAttribute> GetParameterAttribute(Collection<Attribute> attributes) { Collection<ParameterAttribute> paramAttributes = new Collection<ParameterAttribute>(); foreach (Attribute attribute in attributes) { ParameterAttribute paramAttribute = (object)attribute as ParameterAttribute; if (paramAttribute != null) { paramAttributes.Add(paramAttribute); } } return paramAttributes; } /// <summary> /// Gets the validate set attribute from parameter metadata /// </summary> /// <param name="attributes">parameter attributes</param> /// <returns>parameter attributes</returns> private static Collection<ValidateSetAttribute> GetValidateSetAttribute(Collection<Attribute> attributes) { Collection<ValidateSetAttribute> validateSetAttributes = new Collection<ValidateSetAttribute>(); foreach (Attribute attribute in attributes) { ValidateSetAttribute validateSetAttribute = (object)attribute as ValidateSetAttribute; if (validateSetAttribute != null) { validateSetAttributes.Add(validateSetAttribute); } } return validateSetAttributes; } /// <summary> /// Gets the pipeline input type /// </summary> /// <param name="paramAttrib">parameter attribute</param> /// <returns>pipeline input type</returns> private static string GetPipelineInputString(ParameterAttribute paramAttrib) { Debug.Assert(paramAttrib != null); ArrayList values = new ArrayList(); if (paramAttrib.ValueFromPipeline) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByValue)); } if (paramAttrib.ValueFromPipelineByPropertyName) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineByPropertyName)); } if (paramAttrib.ValueFromRemainingArguments) { values.Add(StringUtil.Format(HelpDisplayStrings.PipelineFromRemainingArguments)); } if (values.Count == 0) { return StringUtil.Format(HelpDisplayStrings.FalseShort); } StringBuilder sb = new StringBuilder(); sb.Append(StringUtil.Format(HelpDisplayStrings.TrueShort)); sb.Append(" ("); for (int i = 0; i < values.Count; i++) { sb.Append((string)values[i]); if (i != (values.Count - 1)) { sb.Append(", "); } } sb.Append(")"); return sb.ToString(); } /// <summary> /// Checks if a set of parameters contains any of the common parameters /// </summary> /// <param name="parameters">parameters to check</param> /// <returns>true if it contains common parameters, false otherwise</returns> internal static bool HasCommonParameters(Dictionary<string, ParameterMetadata> parameters) { Collection<string> commonParams = new Collection<string>(); foreach (KeyValuePair<string, ParameterMetadata> parameter in parameters) { if (Cmdlet.CommonParameters.Contains(parameter.Value.Name)) { commonParams.Add(parameter.Value.Name); } } return (commonParams.Count == Cmdlet.CommonParameters.Count); } /// <summary> /// Checks if a parameter is a common workflow parameter /// </summary> /// <param name="name">parameter name</param> /// <returns>true if it is a common parameter, false if not</returns> private static bool IsCommonWorkflowParameter(string name) { foreach (string parameter in CommonParameters.CommonWorkflowParameters) { if (name == parameter) return true; } return false; } /// <summary> /// Checks if the module contains HelpInfoUri /// </summary> /// <param name="module"></param> /// <param name="moduleName"></param> /// <returns></returns> private static bool HasHelpInfoUri(PSModuleInfo module, string moduleName) { // The core module is really a SnapIn, so module will be null if (!String.IsNullOrEmpty(moduleName) && moduleName.Equals(InitialSessionState.CoreModule, StringComparison.OrdinalIgnoreCase)) { return true; } if (module == null) { return false; } return !String.IsNullOrEmpty(module.HelpInfoUri); } } }
using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Compression; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using WalletWasabi.Helpers; using WalletWasabi.Userfacing; namespace WalletWasabi.Packager { public static class Program { #pragma warning disable CS0162 // Unreachable code detected // 0. Dump Client version (or else wrong .msi will be created) - Helpers.Constants.ClientVersion // 1. Publish with Packager. // 2. Build WIX project with Release and x64 configuration. // 3. Sign with Packager, set restore true so the password won't be kept. public const bool DoPublish = true; public const bool DoSign = false; public const bool DoRestoreProgramCs = false; public const string PfxPath = "C:\\digicert.pfx"; public const string ExecutableName = "wassabee"; // https://docs.microsoft.com/en-us/dotnet/articles/core/rid-catalog // BOTTLENECKS: // Tor - win-32, linux-32, osx-64 // .NET Core - win-32, linux-64, osx-64 // Avalonia - win7-32, linux-64, osx-64 // We'll only support x64, if someone complains, we can come back to it. // For 32 bit Windows there needs to be a lot of WIX configuration to be done. private static string[] Targets = new[] { "win7-x64", "linux-x64", "osx-x64" }; private static string VersionPrefix = Constants.ClientVersion.Revision == 0 ? Constants.ClientVersion.ToString(3) : Constants.ClientVersion.ToString(); private static bool OnlyBinaries; private static bool IsContinuousDelivery; public static string PackagerProjectDirectory { get; } = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", "..")); public static string SolutionDirectory { get; } = Path.GetFullPath(Path.Combine(PackagerProjectDirectory, "..")); public static string DesktopProjectDirectory { get; } = Path.GetFullPath(Path.Combine(SolutionDirectory, "WalletWasabi.Fluent.Desktop")); public static string LibraryProjectDirectory { get; } = Path.GetFullPath(Path.Combine(SolutionDirectory, "WalletWasabi")); public static string WixProjectDirectory { get; } = Path.GetFullPath(Path.Combine(SolutionDirectory, "WalletWasabi.WindowsInstaller")); public static string BinDistDirectory { get; } = Path.GetFullPath(Path.Combine(DesktopProjectDirectory, "bin", "dist")); /// <summary> /// Main entry point. /// </summary> [SuppressMessage("Style", "IDE1006:Naming Styles", Justification = "The Main method is the entry point of a C# application")] private static async Task Main(string[] args) { var argsProcessor = new ArgsProcessor(args); // For now this is enough. If you run it on macOS you want to sign. if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { MacSignTools.Sign(); return; } // Only binaries mode is for deterministic builds. OnlyBinaries = argsProcessor.IsOnlyBinariesMode(); IsContinuousDelivery = argsProcessor.IsContinuousDeliveryMode(); ReportStatus(); if (DoPublish || OnlyBinaries) { Publish(); IoHelpers.OpenFolderInFileExplorer(BinDistDirectory); } if (!OnlyBinaries) { if (DoSign) { Sign(); } if (DoRestoreProgramCs) { RestoreProgramCs(); } } } private static void ReportStatus() { if (OnlyBinaries) { Console.WriteLine($"I'll only generate binaries and disregard all other options."); } Console.WriteLine($"{nameof(VersionPrefix)}:\t\t\t{VersionPrefix}"); Console.WriteLine($"{nameof(ExecutableName)}:\t\t\t{ExecutableName}"); Console.WriteLine(); Console.Write($"{nameof(Targets)}:\t\t\t"); foreach (var target in Targets) { if (Targets.Last() != target) { Console.Write($"{target}, "); } else { Console.Write(target); } } Console.WriteLine(); } private static void RestoreProgramCs() { StartProcessAndWaitForExit("cmd", PackagerProjectDirectory, "git checkout -- Program.cs && exit"); } private static void Sign() { foreach (string target in Targets) { if (target.StartsWith("win", StringComparison.OrdinalIgnoreCase)) { string publishedFolder = Path.Combine(BinDistDirectory, target); Console.WriteLine("Move created .msi"); var msiPath = Path.Combine(WixProjectDirectory, "bin", "Release", "Wasabi.msi"); if (!File.Exists(msiPath)) { throw new Exception(".msi does not exist. Expected path: Wasabi.msi."); } var msiFileName = Path.GetFileNameWithoutExtension(msiPath); var newMsiPath = Path.Combine(BinDistDirectory, $"{msiFileName}-{VersionPrefix}.msi"); File.Copy(msiPath, newMsiPath); Console.Write("Enter Code Signing Certificate Password: "); string pfxPassword = PasswordConsole.ReadPassword(); // Sign code with digicert. StartProcessAndWaitForExit("cmd", BinDistDirectory, $"signtool sign /d \"Wasabi Wallet\" /f \"{PfxPath}\" /p {pfxPassword} /t http://timestamp.digicert.com /a \"{newMsiPath}\" && exit"); IoHelpers.TryDeleteDirectoryAsync(publishedFolder).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {publishedFolder}"); } else if (target.StartsWith("osx", StringComparison.OrdinalIgnoreCase)) { string dmgFilePath = Path.Combine(BinDistDirectory, $"Wasabi-{VersionPrefix}.dmg"); if (!File.Exists(dmgFilePath)) { throw new Exception(".dmg does not exist."); } string zipFilePath = Path.Combine(BinDistDirectory, $"Wasabi-osx-{VersionPrefix}.zip"); if (File.Exists(zipFilePath)) { File.Delete(zipFilePath); } } } Console.WriteLine("Signing final files..."); var finalFiles = Directory.GetFiles(BinDistDirectory); foreach (var finalFile in finalFiles) { StartProcessAndWaitForExit("cmd", BinDistDirectory, $"gpg --armor --detach-sign {finalFile} && exit"); StartProcessAndWaitForExit("cmd", WixProjectDirectory, $"git checkout -- ComponentsGenerated.wxs && exit"); } IoHelpers.OpenFolderInFileExplorer(BinDistDirectory); } private static void Publish() { if (Directory.Exists(BinDistDirectory)) { IoHelpers.TryDeleteDirectoryAsync(BinDistDirectory).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {BinDistDirectory}"); } StartProcessAndWaitForExit("cmd", DesktopProjectDirectory, "dotnet clean --configuration Release && exit"); var desktopBinReleaseDirectory = Path.GetFullPath(Path.Combine(DesktopProjectDirectory, "bin", "Release")); var libraryBinReleaseDirectory = Path.GetFullPath(Path.Combine(LibraryProjectDirectory, "bin", "Release")); if (Directory.Exists(desktopBinReleaseDirectory)) { IoHelpers.TryDeleteDirectoryAsync(desktopBinReleaseDirectory).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {desktopBinReleaseDirectory}"); } if (Directory.Exists(libraryBinReleaseDirectory)) { IoHelpers.TryDeleteDirectoryAsync(libraryBinReleaseDirectory).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {libraryBinReleaseDirectory}"); } var deterministicFileNameTag = IsContinuousDelivery ? $"{DateTimeOffset.UtcNow:ddMMyyyy}{DateTimeOffset.UtcNow.TimeOfDay.TotalSeconds}" : VersionPrefix; var deliveryPath = IsContinuousDelivery ? Path.Combine(BinDistDirectory, "cdelivery") : BinDistDirectory; IoHelpers.EnsureDirectoryExists(deliveryPath); Console.WriteLine($"Binaries will be delivered here: {deliveryPath}"); foreach (string target in Targets) { string publishedFolder = Path.Combine(BinDistDirectory, target); string currentBinDistDirectory = publishedFolder; Console.WriteLine(); Console.WriteLine($"{nameof(currentBinDistDirectory)}:\t{currentBinDistDirectory}"); Console.WriteLine(); if (!Directory.Exists(currentBinDistDirectory)) { Directory.CreateDirectory(currentBinDistDirectory); Console.WriteLine($"Created {currentBinDistDirectory}"); } StartProcessAndWaitForExit("dotnet", DesktopProjectDirectory, arguments: "clean"); // https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-publish?tabs=netcore21 // -c|--configuration {Debug|Release} // Defines the build configuration. The default value is Debug. // --force // Forces all dependencies to be resolved even if the last restore was successful. Specifying this flag is the same as deleting the project.assets.json file. // -o|--output <OUTPUT_DIRECTORY> // Specifies the path for the output directory. // If not specified, it defaults to ./bin/[configuration]/[framework]/publish/ for a framework-dependent deployment or // ./bin/[configuration]/[framework]/[runtime]/publish/ for a self-contained deployment. // If the path is relative, the output directory generated is relative to the project file location, not to the current working directory. // --self-contained // Publishes the .NET Core runtime with your application so the runtime does not need to be installed on the target machine. // If a runtime identifier is specified, its default value is true. For more information about the different deployment types, see .NET Core application deployment. // -r|--runtime <RUNTIME_IDENTIFIER> // Publishes the application for a given runtime. This is used when creating a self-contained deployment (SCD). // For a list of Runtime Identifiers (RIDs), see the RID catalog. Default is to publish a framework-dependent deployment (FDD). // --version-suffix <VERSION_SUFFIX> // Defines the version suffix to replace the asterisk (*) in the version field of the project file. // https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-restore?tabs=netcore2x // --disable-parallel // Disables restoring multiple projects in parallel. // --no-cache // Specifies to not cache packages and HTTP requests. // https://github.com/dotnet/docs/issues/7568 // /p:Version=1.2.3.4 // "dotnet publish" supports msbuild command line options like /p:Version=1.2.3.4 string dotnetProcessArgs = string.Join( " ", $"publish", $"--configuration Release", $"--force", $"--output \"{currentBinDistDirectory}\"", $"--self-contained true", $"--runtime \"{target}\"", $"--disable-parallel", $"--no-cache", $"/p:VersionPrefix={VersionPrefix}", $"/p:DebugType=none", $"/p:DebugSymbols=false", $"/p:ErrorReport=none", $"/p:DocumentationFile=\"\"", $"/p:Deterministic=true", $"/p:RestoreLockedMode=true"); StartProcessAndWaitForExit( "dotnet", DesktopProjectDirectory, arguments: dotnetProcessArgs, redirectStandardOutput: true); Tools.ClearSha512Tags(currentBinDistDirectory); // Remove Tor binaries that are not relevant to the platform. var toNotRemove = ""; if (target.StartsWith("win")) { toNotRemove = "win"; } else if (target.StartsWith("linux")) { toNotRemove = "lin"; } else if (target.StartsWith("osx")) { toNotRemove = "osx"; } // Remove binaries that are not relevant to the platform. var binaryFolder = new DirectoryInfo(Path.Combine(currentBinDistDirectory, "Microservices", "Binaries")); foreach (var dir in binaryFolder.EnumerateDirectories()) { if (!dir.Name.Contains(toNotRemove, StringComparison.OrdinalIgnoreCase)) { IoHelpers.TryDeleteDirectoryAsync(dir.FullName).GetAwaiter().GetResult(); } } // Rename the final exe. string oldExecutablePath; string newExecutablePath; if (target.StartsWith("win")) { oldExecutablePath = Path.Combine(currentBinDistDirectory, "WalletWasabi.Fluent.Desktop.exe"); newExecutablePath = Path.Combine(currentBinDistDirectory, $"{ExecutableName}.exe"); // Delete unused executables. File.Delete(Path.Combine(currentBinDistDirectory, "WalletWasabi.Fluent.exe")); File.Delete(Path.Combine(currentBinDistDirectory, "WalletWasabi.Gui.exe")); } else // Linux & OSX { oldExecutablePath = Path.Combine(currentBinDistDirectory, "WalletWasabi.Fluent.Desktop"); newExecutablePath = Path.Combine(currentBinDistDirectory, ExecutableName); // Delete unused executables. File.Delete(Path.Combine(currentBinDistDirectory, "WalletWasabi.Fluent")); File.Delete(Path.Combine(currentBinDistDirectory, "WalletWasabi.Gui")); } File.Move(oldExecutablePath, newExecutablePath); long installedSizeKb = Tools.DirSize(new DirectoryInfo(publishedFolder)) / 1000; if (target.StartsWith("win")) { // IF IT'S IN ONLYBINARIES MODE DON'T DO ANYTHING FANCY PACKAGING AFTER THIS!!! if (OnlyBinaries) { continue; // In Windows build at this moment it does not matter though. } ZipFile.CreateFromDirectory(currentBinDistDirectory, Path.Combine(deliveryPath, $"Wasabi-{deterministicFileNameTag}-{target}.zip")); if (IsContinuousDelivery) { continue; } } else if (target.StartsWith("osx")) { // IF IT'S IN ONLYBINARIES MODE DON'T DO ANYTHING FANCY PACKAGING AFTER THIS!!! if (OnlyBinaries) { continue; } ZipFile.CreateFromDirectory(currentBinDistDirectory, Path.Combine(deliveryPath, $"Wasabi-{deterministicFileNameTag}-{target}.zip")); if (IsContinuousDelivery) { continue; } ZipFile.CreateFromDirectory(currentBinDistDirectory, Path.Combine(BinDistDirectory, $"Wasabi-osx-{VersionPrefix}.zip")); IoHelpers.TryDeleteDirectoryAsync(currentBinDistDirectory).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {currentBinDistDirectory}"); } else if (target.StartsWith("linux")) { // IF IT'S IN ONLYBINARIES MODE DON'T DO ANYTHING FANCY PACKAGING AFTER THIS!!! if (OnlyBinaries) { continue; } ZipFile.CreateFromDirectory(currentBinDistDirectory, Path.Combine(deliveryPath, $"Wasabi-{deterministicFileNameTag}-{target}.zip")); if (IsContinuousDelivery) { continue; } Console.WriteLine("Create Linux .tar.gz"); if (!Directory.Exists(publishedFolder)) { throw new Exception($"{publishedFolder} does not exist."); } var newFolderName = $"Wasabi-{VersionPrefix}"; var newFolderPath = Path.Combine(BinDistDirectory, newFolderName); Directory.Move(publishedFolder, newFolderPath); publishedFolder = newFolderPath; var driveLetterUpper = BinDistDirectory[0]; var driveLetterLower = char.ToLower(driveLetterUpper); var linuxPath = $"/mnt/{driveLetterLower}/{Tools.LinuxPath(BinDistDirectory[3..])}"; var chmodExecutablesArgs = "-type f \\( -name 'wassabee' -o -name 'hwi' -o -name 'bitcoind' -o -name 'tor' \\) -exec chmod u+x {} \\;"; var commands = new[] { "cd ~", $"sudo umount /mnt/{driveLetterLower}", $"sudo mount -t drvfs {driveLetterUpper}: /mnt/{driveLetterLower} -o metadata", $"cd {linuxPath}", $"sudo find ./{newFolderName} -type f -exec chmod 644 {{}} \\;", $"sudo find ./{newFolderName} {chmodExecutablesArgs}", $"tar -pczvf {newFolderName}.tar.gz {newFolderName}" }; string arguments = string.Join(" && ", commands); StartProcessAndWaitForExit("wsl", BinDistDirectory, arguments: arguments); Console.WriteLine("Create Linux .deb"); var debFolderRelativePath = "deb"; var debFolderPath = Path.Combine(BinDistDirectory, debFolderRelativePath); var linuxUsrLocalBinFolder = "/usr/local/bin/"; var debUsrLocalBinFolderRelativePath = Path.Combine(debFolderRelativePath, "usr", "local", "bin"); var debUsrLocalBinFolderPath = Path.Combine(BinDistDirectory, debUsrLocalBinFolderRelativePath); Directory.CreateDirectory(debUsrLocalBinFolderPath); var debUsrAppFolderRelativePath = Path.Combine(debFolderRelativePath, "usr", "share", "applications"); var debUsrAppFolderPath = Path.Combine(BinDistDirectory, debUsrAppFolderRelativePath); Directory.CreateDirectory(debUsrAppFolderPath); var debUsrShareIconsFolderRelativePath = Path.Combine(debFolderRelativePath, "usr", "share", "icons", "hicolor"); var debUsrShareIconsFolderPath = Path.Combine(BinDistDirectory, debUsrShareIconsFolderRelativePath); var debianFolderRelativePath = Path.Combine(debFolderRelativePath, "DEBIAN"); var debianFolderPath = Path.Combine(BinDistDirectory, debianFolderRelativePath); Directory.CreateDirectory(debianFolderPath); newFolderName = "wasabiwallet"; var linuxWasabiWalletFolder = Tools.LinuxPathCombine(linuxUsrLocalBinFolder, newFolderName); var newFolderRelativePath = Path.Combine(debUsrLocalBinFolderRelativePath, newFolderName); newFolderPath = Path.Combine(BinDistDirectory, newFolderRelativePath); Directory.Move(publishedFolder, newFolderPath); var assetsFolder = Path.Combine(DesktopProjectDirectory, "Assets"); var assetsInfo = new DirectoryInfo(assetsFolder); foreach (var file in assetsInfo.EnumerateFiles()) { var number = file.Name.Split(new string[] { "WasabiLogo", ".png" }, StringSplitOptions.RemoveEmptyEntries); if (number.Length == 1 && int.TryParse(number.First(), out int size)) { string destFolder = Path.Combine(debUsrShareIconsFolderPath, $"{size}x{size}", "apps"); Directory.CreateDirectory(destFolder); file.CopyTo(Path.Combine(destFolder, $"{ExecutableName}.png")); } } var controlFilePath = Path.Combine(debianFolderPath, "control"); // License format does not yet work, but should work in the future, it's work in progress: https://bugs.launchpad.net/ubuntu/+source/software-center/+bug/435183 var controlFileContent = $"Package: {ExecutableName}\n" + $"Priority: optional\n" + $"Section: utils\n" + $"Maintainer: nopara73 <[email protected]>\n" + $"Version: {VersionPrefix}\n" + $"Homepage: http://wasabiwallet.io\n" + $"Vcs-Git: git://github.com/zkSNACKs/WalletWasabi.git\n" + $"Vcs-Browser: https://github.com/zkSNACKs/WalletWasabi\n" + $"Architecture: amd64\n" + $"License: Open Source (MIT)\n" + $"Installed-Size: {installedSizeKb}\n" + $"Description: open-source, non-custodial, privacy focused Bitcoin wallet\n" + $" Built-in Tor, CoinJoin, PayJoin and Coin Control features.\n"; File.WriteAllText(controlFilePath, controlFileContent, Encoding.ASCII); var desktopFilePath = Path.Combine(debUsrAppFolderPath, $"{ExecutableName}.desktop"); var desktopFileContent = $"[Desktop Entry]\n" + $"Type=Application\n" + $"Name=Wasabi Wallet\n" + $"StartupWMClass=Wasabi Wallet\n" + $"GenericName=Bitcoin Wallet\n" + $"Comment=Privacy focused Bitcoin wallet.\n" + $"Icon={ExecutableName}\n" + $"Terminal=false\n" + $"Exec={ExecutableName}\n" + $"Categories=Office;Finance;\n" + $"Keywords=bitcoin;wallet;crypto;blockchain;wasabi;privacy;anon;awesome;qwe;asd;\n"; File.WriteAllText(desktopFilePath, desktopFileContent, Encoding.ASCII); var wasabiStarterScriptPath = Path.Combine(debUsrLocalBinFolderPath, $"{ExecutableName}"); var wasabiStarterScriptContent = $"#!/bin/sh\n" + $"{ linuxWasabiWalletFolder.TrimEnd('/')}/{ExecutableName} $@\n"; File.WriteAllText(wasabiStarterScriptPath, wasabiStarterScriptContent, Encoding.ASCII); string debExeLinuxPath = Tools.LinuxPathCombine(newFolderRelativePath, ExecutableName); string debDestopFileLinuxPath = Tools.LinuxPathCombine(debUsrAppFolderRelativePath, $"{ExecutableName}.desktop"); commands = new[] { "cd ~", "sudo umount /mnt/c", "sudo mount -t drvfs C: /mnt/c -o metadata", $"cd {linuxPath}", $"sudo find {Tools.LinuxPath(newFolderRelativePath)} -type f -exec chmod 644 {{}} \\;", $"sudo find {Tools.LinuxPath(newFolderRelativePath)} {chmodExecutablesArgs}", $"sudo chmod -R 0775 {Tools.LinuxPath(debianFolderRelativePath)}", $"sudo chmod -R 0644 {debDestopFileLinuxPath}", $"dpkg --build {Tools.LinuxPath(debFolderRelativePath)} $(pwd)" }; arguments = string.Join(" && ", commands); StartProcessAndWaitForExit("wsl", BinDistDirectory, arguments: arguments); IoHelpers.TryDeleteDirectoryAsync(debFolderPath).GetAwaiter().GetResult(); string oldDeb = Path.Combine(BinDistDirectory, $"{ExecutableName}_{VersionPrefix}_amd64.deb"); string newDeb = Path.Combine(BinDistDirectory, $"Wasabi-{VersionPrefix}.deb"); File.Move(oldDeb, newDeb); IoHelpers.TryDeleteDirectoryAsync(publishedFolder).GetAwaiter().GetResult(); Console.WriteLine($"Deleted {publishedFolder}"); } } } private static string? StartProcessAndWaitForExit(string command, string workingDirectory, string? writeToStandardInput = null, string? arguments = null, bool redirectStandardOutput = false) { var isWriteToStandardInput = !string.IsNullOrWhiteSpace(writeToStandardInput); using var process = Process.Start(new ProcessStartInfo { FileName = command, Arguments = arguments ?? "", RedirectStandardInput = isWriteToStandardInput, RedirectStandardOutput = redirectStandardOutput, WorkingDirectory = workingDirectory }); if (process is null) { throw new InvalidOperationException($"Process '{command}' is invalid."); } if (isWriteToStandardInput) { process.StandardInput.WriteLine(writeToStandardInput); } string? output = null; if (redirectStandardOutput) { output = process.StandardOutput.ReadToEnd(); } process.WaitForExit(); if (process.ExitCode is not 0) { throw new InvalidOperationException($"Process exited with code '{process.ExitCode}'.{ (redirectStandardOutput ? output : "") }"); } return output; } #pragma warning restore CS0162 // Unreachable code detected } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Capabilities.Handlers { public class WebFetchInvDescHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private ILibraryService m_LibraryService; // private object m_fetchLock = new Object(); public WebFetchInvDescHandler(IInventoryService invService, ILibraryService libService) { m_InventoryService = invService; m_LibraryService = libService; } public string FetchInventoryDescendentsRequest(string request, string path, string param, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // lock (m_fetchLock) // { // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Received request {0}", request); // nasty temporary hack here, the linden client falsely // identifies the uuid 00000000-0000-0000-0000-000000000000 // as a string which breaks us // // correctly mark it as a uuid // request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>"); // another hack <integer>1</integer> results in a // System.ArgumentException: Object type System.Int32 cannot // be converted to target type: System.Boolean // request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>"); request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>"); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[WEB FETCH INV DESC HANDLER]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); } ArrayList foldersrequested = (ArrayList)hash["folders"]; string response = ""; string bad_folders_response = ""; for (int i = 0; i < foldersrequested.Count; i++) { string inventoryitemstr = ""; Hashtable inventoryhash = (Hashtable)foldersrequested[i]; LLSDFetchInventoryDescendents llsdRequest = new LLSDFetchInventoryDescendents(); try { LLSDHelpers.DeserialiseOSDMap(inventoryhash, llsdRequest); } catch (Exception e) { m_log.Debug("[WEB FETCH INV DESC HANDLER]: caught exception doing OSD deserialize" + e); } LLSDInventoryDescendents reply = FetchInventoryReply(llsdRequest); if (null == reply) { bad_folders_response += "<uuid>" + llsdRequest.folder_id.ToString() + "</uuid>"; } inventoryitemstr = LLSDHelpers.SerialiseLLSDReply(reply); inventoryitemstr = inventoryitemstr.Replace("<llsd><map><key>folders</key><array>", ""); inventoryitemstr = inventoryitemstr.Replace("</array></map></llsd>", ""); response += inventoryitemstr; } if (response.Length == 0) { /* Viewers expect a bad_folders array when not available */ if (bad_folders_response.Length != 0) { response = "<llsd><map><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array /></map></llsd>"; } } else { if (bad_folders_response.Length != 0) { response = "<llsd><map><key>folders</key><array>" + response + "</array><key>bad_folders</key><array>" + bad_folders_response + "</array></map></llsd>"; } else { response = "<llsd><map><key>folders</key><array>" + response + "</array></map></llsd>"; } } // m_log.DebugFormat("[WEB FETCH INV DESC HANDLER]: Replying to CAPS fetch inventory request"); //m_log.Debug("[WEB FETCH INV DESC HANDLER] "+response); return response; // } } /// <summary> /// Convert an internal inventory folder object into an LLSD object. /// </summary> /// <param name="invFolder"></param> /// <returns></returns> private LLSDInventoryFolder ConvertInventoryFolder(InventoryFolderBase invFolder) { LLSDInventoryFolder llsdFolder = new LLSDInventoryFolder(); llsdFolder.folder_id = invFolder.ID; llsdFolder.parent_id = invFolder.ParentID; llsdFolder.name = invFolder.Name; llsdFolder.type = invFolder.Type; llsdFolder.preferred_type = -1; return llsdFolder; } /// <summary> /// Convert an internal inventory item object into an LLSD object. /// </summary> /// <param name="invItem"></param> /// <returns></returns> private LLSDInventoryItem ConvertInventoryItem(InventoryItemBase invItem) { LLSDInventoryItem llsdItem = new LLSDInventoryItem(); llsdItem.asset_id = invItem.AssetID; llsdItem.created_at = invItem.CreationDate; llsdItem.desc = invItem.Description; llsdItem.flags = (int)invItem.Flags; llsdItem.item_id = invItem.ID; llsdItem.name = invItem.Name; llsdItem.parent_id = invItem.Folder; llsdItem.type = invItem.AssetType; llsdItem.inv_type = invItem.InvType; llsdItem.permissions = new LLSDPermissions(); llsdItem.permissions.creator_id = invItem.CreatorIdAsUuid; llsdItem.permissions.base_mask = (int)invItem.CurrentPermissions; llsdItem.permissions.everyone_mask = (int)invItem.EveryOnePermissions; llsdItem.permissions.group_id = invItem.GroupID; llsdItem.permissions.group_mask = (int)invItem.GroupPermissions; llsdItem.permissions.is_owner_group = invItem.GroupOwned; llsdItem.permissions.next_owner_mask = (int)invItem.NextPermissions; llsdItem.permissions.owner_id = invItem.Owner; llsdItem.permissions.owner_mask = (int)invItem.CurrentPermissions; llsdItem.sale_info = new LLSDSaleInfo(); llsdItem.sale_info.sale_price = invItem.SalePrice; llsdItem.sale_info.sale_type = invItem.SaleType; return llsdItem; } /// <summary> /// Handle the caps inventory descendents fetch. /// </summary> /// <param name="agentID"></param> /// <param name="folderID"></param> /// <param name="ownerID"></param> /// <param name="fetchFolders"></param> /// <param name="fetchItems"></param> /// <param name="sortOrder"></param> /// <param name="version"></param> /// <returns>An empty InventoryCollection if the inventory look up failed</returns> private InventoryCollection Fetch( UUID agentID, UUID folderID, UUID ownerID, bool fetchFolders, bool fetchItems, int sortOrder, out int version, out int descendents) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Fetching folders ({0}), items ({1}) from {2} for agent {3}", // fetchFolders, fetchItems, folderID, agentID); // FIXME MAYBE: We're not handling sortOrder! version = 0; descendents = 0; InventoryFolderImpl fold; if (m_LibraryService != null && m_LibraryService.LibraryRootFolder != null && agentID == m_LibraryService.LibraryRootFolder.Owner) { if ((fold = m_LibraryService.LibraryRootFolder.FindFolder(folderID)) != null) { InventoryCollection ret = new InventoryCollection(); ret.Folders = new List<InventoryFolderBase>(); ret.Items = fold.RequestListOfItems(); descendents = ret.Folders.Count + ret.Items.Count; return ret; } } InventoryCollection contents = new InventoryCollection(); if (folderID != UUID.Zero) { InventoryCollection fetchedContents = m_InventoryService.GetFolderContent(agentID, folderID); if (fetchedContents == null) { m_log.WarnFormat("[WEB FETCH INV DESC HANDLER]: Could not get contents of folder {0} for user {1}", folderID, agentID); return null; } contents = fetchedContents; InventoryFolderBase containingFolder = new InventoryFolderBase(); containingFolder.ID = folderID; containingFolder.Owner = agentID; containingFolder = m_InventoryService.GetFolder(containingFolder); if (containingFolder != null) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Retrieved folder {0} {1} for agent id {2}", // containingFolder.Name, containingFolder.ID, agentID); version = containingFolder.Version; if (fetchItems) { List<InventoryItemBase> itemsToReturn = contents.Items; List<InventoryItemBase> originalItems = new List<InventoryItemBase>(itemsToReturn); // descendents must only include the links, not the linked items we add descendents = originalItems.Count; // Add target items for links in this folder before the links themselves. foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.Link) { InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) itemsToReturn.Insert(0, linkedItem); } } // Now scan for folder links and insert the items they target and those links at the head of the return data foreach (InventoryItemBase item in originalItems) { if (item.AssetType == (int)AssetType.LinkFolder) { InventoryCollection linkedFolderContents = m_InventoryService.GetFolderContent(ownerID, item.AssetID); List<InventoryItemBase> links = linkedFolderContents.Items; itemsToReturn.InsertRange(0, links); foreach (InventoryItemBase link in linkedFolderContents.Items) { // Take care of genuinely broken links where the target doesn't exist // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // rather than having to keep track of every folder requested in the recursion. if (link != null) { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Adding item {0} {1} from folder {2} linked from {3}", // link.Name, (AssetType)link.AssetType, item.AssetID, containingFolder.Name); InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(link.AssetID)); if (linkedItem != null) itemsToReturn.Insert(0, linkedItem); } } } } } // foreach (InventoryItemBase item in contents.Items) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Returning item {0}, type {1}, parent {2} in {3} {4}", // item.Name, (AssetType)item.AssetType, item.Folder, containingFolder.Name, containingFolder.ID); // } // ===== // // foreach (InventoryItemBase linkedItem in linkedItemsToAdd) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Inserted linked item {0} for link in folder {1} for agent {2}", // linkedItem.Name, folderID, agentID); // // contents.Items.Add(linkedItem); // } // // // If the folder requested contains links, then we need to send those folders first, otherwise the links // // will be broken in the viewer. // HashSet<UUID> linkedItemFolderIdsToSend = new HashSet<UUID>(); // foreach (InventoryItemBase item in contents.Items) // { // if (item.AssetType == (int)AssetType.Link) // { // InventoryItemBase linkedItem = m_InventoryService.GetItem(new InventoryItemBase(item.AssetID)); // // // Take care of genuinely broken links where the target doesn't exist // // HACK: Also, don't follow up links that just point to other links. In theory this is legitimate, // // but no viewer has been observed to set these up and this is the lazy way of avoiding cycles // // rather than having to keep track of every folder requested in the recursion. // if (linkedItem != null && linkedItem.AssetType != (int)AssetType.Link) // { // // We don't need to send the folder if source and destination of the link are in the same // // folder. // if (linkedItem.Folder != containingFolder.ID) // linkedItemFolderIdsToSend.Add(linkedItem.Folder); // } // } // } // // foreach (UUID linkedItemFolderId in linkedItemFolderIdsToSend) // { // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Recursively fetching folder {0} linked by item in folder {1} for agent {2}", // linkedItemFolderId, folderID, agentID); // // int dummyVersion; // InventoryCollection linkedCollection // = Fetch( // agentID, linkedItemFolderId, ownerID, fetchFolders, fetchItems, sortOrder, out dummyVersion); // // InventoryFolderBase linkedFolder = new InventoryFolderBase(linkedItemFolderId); // linkedFolder.Owner = agentID; // linkedFolder = m_InventoryService.GetFolder(linkedFolder); // //// contents.Folders.AddRange(linkedCollection.Folders); // // contents.Folders.Add(linkedFolder); // contents.Items.AddRange(linkedCollection.Items); // } // } } } else { // Lost items don't really need a version version = 1; } return contents; } /// <summary> /// Construct an LLSD reply packet to a CAPS inventory request /// </summary> /// <param name="invFetch"></param> /// <returns></returns> private LLSDInventoryDescendents FetchInventoryReply(LLSDFetchInventoryDescendents invFetch) { LLSDInventoryDescendents reply = new LLSDInventoryDescendents(); LLSDInventoryFolderContents contents = new LLSDInventoryFolderContents(); contents.agent_id = invFetch.owner_id; contents.owner_id = invFetch.owner_id; contents.folder_id = invFetch.folder_id; reply.folders.Array.Add(contents); InventoryCollection inv; int version = 0; int descendents = 0; inv = Fetch( invFetch.owner_id, invFetch.folder_id, invFetch.owner_id, invFetch.fetch_folders, invFetch.fetch_items, invFetch.sort_order, out version, out descendents); if (inv == null) { return null; } if (inv != null && inv.Folders != null) { foreach (InventoryFolderBase invFolder in inv.Folders) { contents.categories.Array.Add(ConvertInventoryFolder(invFolder)); } descendents += inv.Folders.Count; } if (inv != null && inv.Items != null) { foreach (InventoryItemBase invItem in inv.Items) { contents.items.Array.Add(ConvertInventoryItem(invItem)); } } contents.descendents = descendents; contents.version = version; // m_log.DebugFormat( // "[WEB FETCH INV DESC HANDLER]: Replying to request for folder {0} (fetch items {1}, fetch folders {2}) with {3} items and {4} folders for agent {5}", // invFetch.folder_id, // invFetch.fetch_items, // invFetch.fetch_folders, // contents.items.Array.Count, // contents.categories.Array.Count, // invFetch.owner_id); return reply; } } }
// 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.IO; using System.Linq; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { [ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // httpsys component missing in Nano. public class HttpRequestStreamTests : IDisposable { private HttpListenerFactory _factory; private HttpListener _listener; private GetContextHelper _helper; private const int TimeoutMilliseconds = 60*1000; private readonly ITestOutputHelper _output; public HttpRequestStreamTests(ITestOutputHelper output) { _factory = new HttpListenerFactory(); _listener = _factory.GetListener(); _helper = new GetContextHelper(_listener, _factory.ListeningUrl); _output = output; } public void Dispose() { _factory.Dispose(); _helper.Dispose(); } // Try to read 'length' bytes from stream or fail after timeout. private async Task<int> ReadLengthAsync(Stream stream, byte[] array, int offset, int length) { int remaining = length; int readLength; do { readLength = await TaskTimeoutExtensions.TimeoutAfter(stream.ReadAsync(array, offset, remaining), TimeoutMilliseconds); if (readLength <= 0) { break; } remaining -= readLength; offset += readLength; } while (remaining > 0); if (remaining != 0) { _output.WriteLine("Expected {0} bytes but got {1}", length, length-remaining); } return length - remaining; } // Synchronous version of ReadLengthAsync above. private int ReadLength(Stream stream, byte[] array, int offset, int length) { int remaining = length; int readLength; do { readLength = stream.Read(array, offset, remaining); if (readLength <= 0) { break; } remaining -= readLength; offset += readLength; } while (remaining > 0); if (remaining != 0) { _output.WriteLine("Expected {0} bytes but got {1}", length, length-remaining); } return length - remaining; } [Theory] [InlineData(true, "")] [InlineData(false, "")] [InlineData(true, "Non-Empty")] [InlineData(false, "Non-Empty")] public async Task Read_FullLengthAsynchronous_Success(bool transferEncodingChunked, string text) { byte[] expected = Encoding.UTF8.GetBytes(text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text)); HttpListenerContext context = await contextTask; if (transferEncodingChunked) { Assert.Equal(-1, context.Request.ContentLength64); Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]); } else { Assert.Equal(expected.Length, context.Request.ContentLength64); Assert.Null(context.Request.Headers["Transfer-Encoding"]); } byte[] buffer = new byte[expected.Length]; int bytesRead = await ReadLengthAsync(context.Request.InputStream, buffer, 0, expected.Length); Assert.Equal(expected.Length, bytesRead); Assert.Equal(expected, buffer); // Subsequent reads don't do anything. Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(expected, buffer); context.Response.Close(); using (HttpResponseMessage response = await clientTask) { Assert.Equal(200, (int)response.StatusCode); } } } [Theory] [InlineData(true, "")] [InlineData(false, "")] [InlineData(true, "Non-Empty")] [InlineData(false, "Non-Empty")] public async Task Read_FullLengthAsynchronous_PadBuffer_Success(bool transferEncodingChunked, string text) { byte[] expected = Encoding.UTF8.GetBytes(text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text)); HttpListenerContext context = await contextTask; if (transferEncodingChunked) { Assert.Equal(-1, context.Request.ContentLength64); Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]); } else { Assert.Equal(expected.Length, context.Request.ContentLength64); Assert.Null(context.Request.Headers["Transfer-Encoding"]); } const int pad = 128; // Add padding at beginning and end to test for correct offset/size handling byte[] buffer = new byte[pad + expected.Length + pad]; int bytesRead = await ReadLengthAsync(context.Request.InputStream, buffer, pad, expected.Length); Assert.Equal(expected.Length, bytesRead); Assert.Equal(expected, buffer.Skip(pad).Take(bytesRead)); // Subsequent reads don't do anything. Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, pad, 1)); context.Response.Close(); using (HttpResponseMessage response = await clientTask) { Assert.Equal(200, (int)response.StatusCode); } } } [Theory] [InlineData(true, "")] [InlineData(false, "")] [InlineData(true, "Non-Empty")] [InlineData(false, "Non-Empty")] public async Task Read_FullLengthSynchronous_Success(bool transferEncodingChunked, string text) { byte[] expected = Encoding.UTF8.GetBytes(text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(text)); HttpListenerContext context = await contextTask; if (transferEncodingChunked) { Assert.Equal(-1, context.Request.ContentLength64); Assert.Equal("chunked", context.Request.Headers["Transfer-Encoding"]); } else { Assert.Equal(expected.Length, context.Request.ContentLength64); Assert.Null(context.Request.Headers["Transfer-Encoding"]); } byte[] buffer = new byte[expected.Length]; int bytesRead = ReadLength(context.Request.InputStream, buffer, 0, buffer.Length); Assert.Equal(expected.Length, bytesRead); Assert.Equal(expected, buffer); // Subsequent reads don't do anything. Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length)); Assert.Equal(expected, buffer); context.Response.Close(); using (HttpResponseMessage response = await clientTask) { Assert.Equal(200, (int)response.StatusCode); } } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_LargeLengthAsynchronous_Success(bool transferEncodingChunked) { var rand = new Random(42); byte[] expected = Enumerable .Range(0, 128*1024 + 1) // More than 128kb .Select(_ => (byte)('a' + rand.Next(0, 26))) .ToArray(); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected)); HttpListenerContext context = await contextTask; // If the size is greater than 128K, then we limit the size, and have to do multiple reads on // Windows, which uses http.sys internally. byte[] buffer = new byte[expected.Length]; int totalRead = 0; while (totalRead < expected.Length) { int bytesRead = await context.Request.InputStream.ReadAsync(buffer, totalRead, expected.Length - totalRead); Assert.InRange(bytesRead, 1, expected.Length - totalRead); totalRead += bytesRead; } // Subsequent reads don't do anything. Assert.Equal(0, await context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length)); Assert.Equal(expected, buffer); context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_LargeLengthSynchronous_Success(bool transferEncodingChunked) { var rand = new Random(42); byte[] expected = Enumerable .Range(0, 128 * 1024 + 1) // More than 128kb .Select(_ => (byte)('a' + rand.Next(0, 26))) .ToArray(); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new ByteArrayContent(expected)); HttpListenerContext context = await contextTask; // If the size is greater than 128K, then we limit the size, and have to do multiple reads on // Windows, which uses http.sys internally. byte[] buffer = new byte[expected.Length]; int totalRead = 0; while (totalRead < expected.Length) { int bytesRead = context.Request.InputStream.Read(buffer, totalRead, expected.Length - totalRead); Assert.InRange(bytesRead, 1, expected.Length - totalRead); totalRead += bytesRead; } // Subsequent reads don't do anything. Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length)); Assert.Equal(expected, buffer); context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_TooMuchAsynchronous_Success(bool transferEncodingChunked) { const string Text = "Some-String"; byte[] expected = Encoding.UTF8.GetBytes(Text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text)); HttpListenerContext context = await contextTask; byte[] buffer = new byte[expected.Length + 5]; int bytesRead = await ReadLengthAsync(context.Request.InputStream, buffer, 0, buffer.Length); Assert.Equal(expected.Length, bytesRead); Assert.Equal(expected.Concat(new byte[5]), buffer); context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_TooMuchSynchronous_Success(bool transferEncodingChunked) { const string Text = "Some-String"; byte[] expected = Encoding.UTF8.GetBytes(Text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text)); HttpListenerContext context = await contextTask; byte[] buffer = new byte[expected.Length + 5]; int bytesRead = ReadLength(context.Request.InputStream, buffer, 0, buffer.Length); Assert.Equal(expected.Length, bytesRead); Assert.Equal(expected.Concat(new byte[5]), buffer); context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_NotEnoughThenCloseAsynchronous_Success(bool transferEncodingChunked) { const string Text = "Some-String"; byte[] expected = Encoding.UTF8.GetBytes(Text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text)); HttpListenerContext context = await contextTask; byte[] buffer = new byte[expected.Length - 5]; int bytesRead = await ReadLengthAsync(context.Request.InputStream, buffer, 0, buffer.Length); Assert.Equal(buffer.Length, bytesRead); context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_Disposed_ReturnsZero(bool transferEncodingChunked) { const string Text = "Some-String"; int bufferSize = Encoding.UTF8.GetByteCount(Text); Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = transferEncodingChunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent(Text)); HttpListenerContext context = await contextTask; context.Request.InputStream.Close(); byte[] buffer = new byte[bufferSize]; Assert.Equal(0, context.Request.InputStream.Read(buffer, 0, buffer.Length)); Assert.Equal(new byte[bufferSize], buffer); IAsyncResult result = context.Request.InputStream.BeginRead(buffer, 0, buffer.Length, null, null); Assert.Equal(0, context.Request.InputStream.EndRead(result)); Assert.Equal(new byte[bufferSize], buffer); context.Response.Close(); await clientTask; } } [Fact] public async Task CanSeek_Get_ReturnsFalse() { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { Assert.False(inputStream.CanSeek); Assert.Throws<NotSupportedException>(() => inputStream.Length); Assert.Throws<NotSupportedException>(() => inputStream.SetLength(1)); Assert.Throws<NotSupportedException>(() => inputStream.Position); Assert.Throws<NotSupportedException>(() => inputStream.Position = 1); Assert.Throws<NotSupportedException>(() => inputStream.Seek(0, SeekOrigin.Begin)); } context.Response.Close(); await clientTask; } } [Fact] public async Task CanRead_Get_ReturnsTrue() { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { Assert.True(inputStream.CanRead); } context.Response.Close(); await clientTask; } } [Fact] public async Task CanWrite_Get_ReturnsFalse() { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { Assert.False(inputStream.CanWrite); Assert.Throws<InvalidOperationException>(() => inputStream.Write(new byte[0], 0, 0)); await Assert.ThrowsAsync<InvalidOperationException>(() => inputStream.WriteAsync(new byte[0], 0, 0)); Assert.Throws<InvalidOperationException>(() => inputStream.EndWrite(null)); // Flushing the output stream is a no-op. inputStream.Flush(); Assert.Equal(Task.CompletedTask, inputStream.FlushAsync(CancellationToken.None)); } context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task Read_NullBuffer_ThrowsArgumentNullException(bool chunked) { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { AssertExtensions.Throws<ArgumentNullException>("buffer", () => inputStream.Read(null, 0, 0)); await AssertExtensions.ThrowsAsync<ArgumentNullException>("buffer", () => inputStream.ReadAsync(null, 0, 0)); } context.Response.Close(); await clientTask; } } [Theory] [InlineData(-1, true)] [InlineData(3, true)] [InlineData(-1, false)] [InlineData(3, false)] public async Task Read_InvalidOffset_ThrowsArgumentOutOfRangeException(int offset, bool chunked) { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => inputStream.Read(new byte[2], offset, 0)); await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("offset", () => inputStream.ReadAsync(new byte[2], offset, 0)); } context.Response.Close(); await clientTask; } } [Theory] [InlineData(0, 3, true)] [InlineData(1, 2, true)] [InlineData(2, 1, true)] [InlineData(0, 3, false)] [InlineData(1, 2, false)] [InlineData(2, 1, false)] public async Task Read_InvalidOffsetSize_ThrowsArgumentOutOfRangeException(int offset, int size, bool chunked) { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { AssertExtensions.Throws<ArgumentOutOfRangeException>("size", () => inputStream.Read(new byte[2], offset, size)); await AssertExtensions.ThrowsAsync<ArgumentOutOfRangeException>("size", () => inputStream.ReadAsync(new byte[2], offset, size)); } context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task EndRead_NullAsyncResult_ThrowsArgumentNullException(bool chunked) { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { AssertExtensions.Throws<ArgumentNullException>("asyncResult", () => inputStream.EndRead(null)); } context.Response.Close(); await clientTask; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task EndRead_InvalidAsyncResult_ThrowsArgumentException(bool chunked) { using (HttpClient client = new HttpClient()) { Task<HttpListenerContext> contextTask1 = _listener.GetContextAsync(); client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask1 = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context1 = await contextTask1; HttpListenerRequest request1 = context1.Request; Task<HttpListenerContext> contextTask2 = _listener.GetContextAsync(); client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask2 = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context2 = await contextTask2; HttpListenerRequest request2 = context2.Request; using (Stream inputStream1 = request1.InputStream) using (Stream inputStream2 = request2.InputStream) { IAsyncResult beginReadResult = inputStream1.BeginRead(new byte[0], 0, 0, null, null); AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(new CustomAsyncResult())); AssertExtensions.Throws<ArgumentException>("asyncResult", () => inputStream2.EndRead(beginReadResult)); } context1.Response.Close(); await clientTask1; context2.Response.Close(); await clientTask2; } } [Theory] [InlineData(true)] [InlineData(false)] public async Task EndRead_CalledTwice_ThrowsInvalidOperationException(bool chunked) { Task<HttpListenerContext> contextTask = _listener.GetContextAsync(); using (HttpClient client = new HttpClient()) { client.DefaultRequestHeaders.TransferEncodingChunked = chunked; Task<HttpResponseMessage> clientTask = client.PostAsync(_factory.ListeningUrl, new StringContent("Hello")); HttpListenerContext context = await contextTask; HttpListenerRequest request = context.Request; using (Stream inputStream = request.InputStream) { IAsyncResult beginReadResult = inputStream.BeginRead(new byte[0], 0, 0, null, null); inputStream.EndRead(beginReadResult); Assert.Throws<InvalidOperationException>(() => inputStream.EndRead(beginReadResult)); } context.Response.Close(); await clientTask; } } [Fact] public async Task Read_FromClosedConnectionAsynchronously_ThrowsHttpListenerException() { const string Text = "Some-String"; byte[] expected = Encoding.UTF8.GetBytes(Text); using (Socket client = _factory.GetConnectedSocket()) { // Send a header to the HttpListener to give it a context. // Note: It's important here that we don't send the content. // If the content is missing, then the HttpListener needs // to get the content. However, the socket has been closed // before the reading of the content, so reading should fail. client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true)); HttpListenerContext context = await _listener.GetContextAsync(); // Disconnect the Socket from the HttpListener. Helpers.WaitForSocketShutdown(client); // Reading from a closed connection should fail. byte[] buffer = new byte[expected.Length]; await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length)); await Assert.ThrowsAsync<HttpListenerException>(() => context.Request.InputStream.ReadAsync(buffer, 0, buffer.Length)); } } [Fact] public async Task Read_FromClosedConnectionSynchronously_ThrowsHttpListenerException() { const string Text = "Some-String"; byte[] expected = Encoding.UTF8.GetBytes(Text); using (Socket client = _factory.GetConnectedSocket()) { // Send a header to the HttpListener to give it a context. // Note: It's important here that we don't send the content. // If the content is missing, then the HttpListener needs // to get the content. However, the socket has been closed // before the reading of the content, so reading should fail. client.Send(_factory.GetContent(RequestTypes.POST, Text, headerOnly: true)); HttpListenerContext context = await _listener.GetContextAsync(); // Disconnect the Socket from the HttpListener. Helpers.WaitForSocketShutdown(client); // Reading from a closed connection should fail. byte[] buffer = new byte[expected.Length]; Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length)); Assert.Throws<HttpListenerException>(() => context.Request.InputStream.Read(buffer, 0, buffer.Length)); } } } }
// 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.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// The Simple NamedPipe tests cover potentially every-day scenarios that are shared /// by all NamedPipes whether they be Server/Client or In/Out/Inout. /// </summary> public abstract class NamedPipeTest_Simple : NamedPipeTestBase { /// <summary> /// Yields every combination of testing options for the OneWayReadWrites test /// </summary> /// <returns></returns> public static IEnumerable<object[]> OneWayReadWritesMemberData() { var options = new[] { PipeOptions.None, PipeOptions.Asynchronous }; var bools = new[] { false, true }; foreach (PipeOptions serverOption in options) foreach (PipeOptions clientOption in options) foreach (bool asyncServerOps in bools) foreach (bool asyncClientOps in bools) yield return new object[] { serverOption, clientOption, asyncServerOps, asyncClientOps }; } [Theory] [MemberData(nameof(OneWayReadWritesMemberData))] public async Task OneWayReadWrites(PipeOptions serverOptions, PipeOptions clientOptions, bool asyncServerOps, bool asyncClientOps) { using (NamedPipePair pair = CreateNamedPipePair(serverOptions, clientOptions)) { NamedPipeClientStream client = pair.clientStream; NamedPipeServerStream server = pair.serverStream; byte[] received = new byte[] { 0 }; Task clientTask = Task.Run(async () => { if (asyncClientOps) { await client.ConnectAsync(); if (pair.writeToServer) { received = await ReadBytesAsync(client, sendBytes.Length); } else { await WriteBytesAsync(client, sendBytes); } } else { client.Connect(); if (pair.writeToServer) { received = ReadBytes(client, sendBytes.Length); } else { WriteBytes(client, sendBytes); } } }); if (asyncServerOps) { await server.WaitForConnectionAsync(); if (pair.writeToServer) { await WriteBytesAsync(server, sendBytes); } else { received = await ReadBytesAsync(server, sendBytes.Length); } } else { server.WaitForConnection(); if (pair.writeToServer) { WriteBytes(server, sendBytes); } else { received = ReadBytes(server, sendBytes.Length); } } await clientTask; Assert.Equal(sendBytes, received); server.Disconnect(); Assert.False(server.IsConnected); } } [Fact] public async Task ClonedServer_ActsAsOriginalServer() { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream serverBase = pair.serverStream; NamedPipeClientStream client = pair.clientStream; pair.Connect(); if (pair.writeToServer) { Task<int> clientTask = client.ReadAsync(received1, 0, received1.Length); using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.Out, false, true, serverBase.SafePipeHandle)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(1, client.NumberOfServerInstances); } server.Write(msg1, 0, msg1.Length); int receivedLength = await clientTask; Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); } } else { Task clientTask = client.WriteAsync(msg1, 0, msg1.Length); using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.In, false, true, serverBase.SafePipeHandle)) { int receivedLength = server.Read(received1, 0, msg1.Length); Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); await clientTask; } } } } [Fact] public async Task ClonedClient_ActsAsOriginalClient() { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); NamedPipeServerStream server = pair.serverStream; if (pair.writeToServer) { using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.In, false, true, pair.clientStream.SafePipeHandle)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(1, client.NumberOfServerInstances); } Task<int> clientTask = client.ReadAsync(received1, 0, received1.Length); server.Write(msg1, 0, msg1.Length); int receivedLength = await clientTask; Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); } } else { using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.Out, false, true, pair.clientStream.SafePipeHandle)) { Task clientTask = client.WriteAsync(msg1, 0, msg1.Length); int receivedLength = server.Read(received1, 0, msg1.Length); Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); await clientTask; } } } } [Fact] public void ConnectOnAlreadyConnectedClient_Throws_InvalidOperationException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); Assert.True(client.IsConnected); Assert.True(server.IsConnected); Assert.Throws<InvalidOperationException>(() => client.Connect()); } } [Fact] public void WaitForConnectionOnAlreadyConnectedServer_Throws_InvalidOperationException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); Assert.True(client.IsConnected); Assert.True(server.IsConnected); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); } } [Fact] public async Task CancelTokenOn_ServerWaitForConnectionAsync_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; var ctx = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // cancellation token after the operation has been initiated { Task serverWaitTimeout = server.WaitForConnectionAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWaitTimeout); } ctx.Cancel(); Assert.True(server.WaitForConnectionAsync(ctx.Token).IsCanceled); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_ServerWaitForConnectionAsyncWithOuterCancellation_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; Task waitForConnectionTask = server.WaitForConnectionAsync(CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => waitForConnectionTask); Assert.True(waitForConnectionTask.IsCanceled); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_ServerWaitForConnectionAsyncWithOuterCancellation_Throws_IOException() { using (NamedPipePair pair = CreateNamedPipePair()) { var cts = new CancellationTokenSource(); NamedPipeServerStream server = pair.serverStream; Task waitForConnectionTask = server.WaitForConnectionAsync(cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => waitForConnectionTask); } } [Fact] public async Task OperationsOnDisconnectedServer() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); // fails because allowed connections is set to 1 server.Disconnect(); Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // double disconnect byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (pair.writeToServer) { Assert.Throws<InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); }); } else { Assert.Throws<InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.ReadByte()); Assert.Throws<InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => server.Flush()); Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.GetImpersonationUserName()); } } [Fact] public virtual async Task OperationsOnDisconnectedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; pair.Connect(); Assert.Throws<InvalidOperationException>(() => client.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => client.Connect()); await Assert.ThrowsAsync<InvalidOperationException>(() => client.ConnectAsync()); server.Disconnect(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (!pair.writeToServer) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // writes on Unix may still succeed after other end disconnects, due to socket being used { // Pipe is broken Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(5)); Assert.Throws<IOException>(() => { client.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws<IOException>(() => client.Flush()); Assert.Throws<IOException>(() => client.NumberOfServerInstances); } } else { // Nothing for the client to read, but no exception throwing Assert.Equal(0, client.Read(buffer, 0, buffer.Length)); Assert.Equal(-1, client.ReadByte()); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // NumberOfServerInstances not supported on Unix { Assert.Throws<PlatformNotSupportedException>(() => client.NumberOfServerInstances); } } Assert.Throws<InvalidOperationException>(() => client.IsMessageComplete); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unix implemented on sockets, where disposal information doesn't propagate public async Task Windows_OperationsOnNamedServerWithDisposedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); pair.clientStream.Dispose(); Assert.Throws<IOException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<IOException>(() => server.WaitForConnectionAsync()); Assert.Throws<IOException>(() => server.GetImpersonationUserName()); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/1011 [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix implemented on sockets, where disposal information doesn't propagate public async Task Unix_OperationsOnNamedServerWithDisposedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); pair.clientStream.Dispose(); // On Unix, the server still thinks that it is connected after client Disposal. Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); Assert.NotNull(server.GetImpersonationUserName()); } } [Fact] public void OperationsOnUnconnectedServer() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; // doesn't throw exceptions PipeTransmissionMode transmitMode = server.TransmissionMode; Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (pair.writeToServer) { Assert.Equal(0, server.OutBufferSize); Assert.Throws<InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); }); } else { Assert.Equal(0, server.InBufferSize); PipeTransmissionMode readMode = server.ReadMode; Assert.Throws<InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.ReadByte()); Assert.Throws<InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // disconnect when not connected Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); } } [Fact] public void OperationsOnUnconnectedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (client.CanRead) { Assert.Throws<InvalidOperationException>(() => client.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => client.ReadByte()); Assert.Throws<InvalidOperationException>(() => { client.ReadAsync(buffer, 0, buffer.Length); }); Assert.Throws<InvalidOperationException>(() => client.ReadMode); Assert.Throws<InvalidOperationException>(() => client.ReadMode = PipeTransmissionMode.Byte); } if (client.CanWrite) { Assert.Throws<InvalidOperationException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => client.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { client.WriteAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => client.NumberOfServerInstances); Assert.Throws<InvalidOperationException>(() => client.TransmissionMode); Assert.Throws<InvalidOperationException>(() => client.InBufferSize); Assert.Throws<InvalidOperationException>(() => client.OutBufferSize); Assert.Throws<InvalidOperationException>(() => client.SafePipeHandle); } } [Fact] public async Task DisposedServerPipe_Throws_ObjectDisposedException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream pipe = pair.serverStream; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Disconnect()); Assert.Throws<ObjectDisposedException>(() => pipe.GetImpersonationUserName()); Assert.Throws<ObjectDisposedException>(() => pipe.WaitForConnection()); await Assert.ThrowsAsync<ObjectDisposedException>(() => pipe.WaitForConnectionAsync()); } } [Fact] public async Task DisposedClientPipe_Throws_ObjectDisposedException() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); NamedPipeClientStream pipe = pair.clientStream; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Connect()); await Assert.ThrowsAsync<ObjectDisposedException>(() => pipe.ConnectAsync()); Assert.Throws<ObjectDisposedException>(() => pipe.NumberOfServerInstances); } } [Fact] public async Task ReadAsync_DisconnectDuringRead_Returns0() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); Task<int> readTask; if (pair.clientStream.CanRead) { readTask = pair.clientStream.ReadAsync(new byte[1], 0, 1); pair.serverStream.Dispose(); } else { readTask = pair.serverStream.ReadAsync(new byte[1], 0, 1); pair.clientStream.Dispose(); } Assert.Equal(0, await readTask); } } [PlatformSpecific(TestPlatforms.Windows)] // Unix named pipes are on sockets, where small writes with an empty buffer will succeed immediately [Fact] public async Task WriteAsync_DisconnectDuringWrite_Throws() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); Task writeTask; if (pair.clientStream.CanWrite) { writeTask = pair.clientStream.WriteAsync(new byte[1], 0, 1); pair.serverStream.Dispose(); } else { writeTask = pair.serverStream.WriteAsync(new byte[1], 0, 1); pair.clientStream.Dispose(); } await Assert.ThrowsAsync<IOException>(() => writeTask); } } [Fact] [ActiveIssue("dotnet/corefx #16934", TargetFrameworkMonikers.NetFramework)] //Hangs forever in desktop as it doesn't have cancellation support public async Task Server_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead && client.CanWrite) { var ctx1 = new CancellationTokenSource(); Task<int> serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); ctx1.Cancel(); Assert.True(server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } if (server.CanWrite) { var ctx1 = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // On Unix WriteAsync's aren't cancelable once initiated { Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); } ctx1.Cancel(); Assert.True(server.WriteAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_Server_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead) { Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); Assert.True(serverReadToken.IsCanceled); } if (server.CanWrite) { Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); Assert.True(serverWriteToken.IsCanceled); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_Server_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead) { var cts = new CancellationTokenSource(); Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); } if (server.CanWrite) { var cts = new CancellationTokenSource(); Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); } } } [Fact] [ActiveIssue("dotnet/corefx #16934", TargetFrameworkMonikers.NetFramework)] //Hangs forever in desktop as it doesn't have cancellation support public async Task Client_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { var ctx1 = new CancellationTokenSource(); Task serverReadToken = client.ReadAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); Assert.True(client.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } if (client.CanWrite) { var ctx1 = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // On Unix WriteAsync's aren't cancelable once initiated { Task serverWriteToken = client.WriteAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); } ctx1.Cancel(); Assert.True(client.WriteAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_Client_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientReadToken); Assert.True(clientReadToken.IsCanceled); } if (client.CanWrite) { Task clientWriteToken = client.WriteAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientWriteToken); Assert.True(clientWriteToken.IsCanceled); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_Client_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { var cts = new CancellationTokenSource(); Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientReadToken); } if (client.CanWrite) { var cts = new CancellationTokenSource(); Task clientWriteToken = client.WriteAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientWriteToken); } } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ManyConcurrentOperations(bool cancelable) { using (NamedPipePair pair = CreateNamedPipePair(PipeOptions.Asynchronous, PipeOptions.Asynchronous)) { await Task.WhenAll(pair.serverStream.WaitForConnectionAsync(), pair.clientStream.ConnectAsync()); const int NumOps = 100; const int DataPerOp = 512; byte[] sendingData = new byte[NumOps * DataPerOp]; byte[] readingData = new byte[sendingData.Length]; new Random().NextBytes(sendingData); var cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None; Stream reader = pair.writeToServer ? (Stream)pair.clientStream : pair.serverStream; Stream writer = pair.writeToServer ? (Stream)pair.serverStream : pair.clientStream; var reads = new Task<int>[NumOps]; var writes = new Task[NumOps]; for (int i = 0; i < reads.Length; i++) reads[i] = reader.ReadAsync(readingData, i * DataPerOp, DataPerOp, cancellationToken); for (int i = 0; i < reads.Length; i++) writes[i] = writer.WriteAsync(sendingData, i * DataPerOp, DataPerOp, cancellationToken); const int WaitTimeout = 30000; Assert.True(Task.WaitAll(writes, WaitTimeout)); Assert.True(Task.WaitAll(reads, WaitTimeout)); // The data of each write may not be written atomically, and as such some of the data may be // interleaved rather than entirely in the order written. Assert.Equal(sendingData.OrderBy(b => b), readingData.OrderBy(b => b)); } } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerInOutRead_ClientInOutWrite : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, clientOptions); ret.writeToServer = false; return ret; } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerInOutWrite_ClientInOutRead : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, clientOptions); ret.writeToServer = true; return ret; } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerInOut_ClientIn : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.In, clientOptions); ret.writeToServer = true; return ret; } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerInOut_ClientOut : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, clientOptions); ret.writeToServer = false; return ret; } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerOut_ClientIn : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.In, clientOptions); ret.writeToServer = true; return ret; } } [ActiveIssue(21392, TargetFrameworkMonikers.Uap)] public class NamedPipeTest_Simple_ServerIn_ClientOut : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, clientOptions); ret.writeToServer = false; return ret; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using d60.Cirqus.Aggregates; using d60.Cirqus.Commands; using d60.Cirqus.Events; using d60.Cirqus.Exceptions; using d60.Cirqus.Extensions; using d60.Cirqus.Logging; using d60.Cirqus.Logging.Null; using d60.Cirqus.Numbers; using d60.Cirqus.Serialization; using d60.Cirqus.Tests.Contracts.EventStore.Factories; using d60.Cirqus.Tests.Extensions; using NUnit.Framework; namespace d60.Cirqus.Tests.Contracts.EventStore { [Description("Contract test for event stores. Verifies that event store implementation and sequence number generation works in tandem")] [TestFixture(typeof(MongoDbEventStoreFactory), Category = TestCategories.MongoDb)] [TestFixture(typeof(InMemoryEventStoreFactory))] [TestFixture(typeof(MsSqlEventStoreFactory), Category = TestCategories.MsSql)] [TestFixture(typeof(PostgreSqlEventStoreFactory), Category = TestCategories.PostgreSql)] [TestFixture(typeof(NtfsEventStoreFactory))] [TestFixture(typeof(SQLiteEventStoreFactory))] [TestFixture(typeof(CachedEventStoreFactory), Category = TestCategories.MongoDb, Description = "Uses MongoDB behind the scenes")] public class EventStoreTest<TEventStoreFactory> : FixtureBase where TEventStoreFactory : IEventStoreFactory, new() { TEventStoreFactory _eventStoreFactory; IEventStore _eventStore; protected override void DoSetUp() { _eventStoreFactory = new TEventStoreFactory(); _eventStore = _eventStoreFactory.GetEventStore(); if (_eventStore is IDisposable) { RegisterForDisposal((IDisposable)_eventStore); } } [Test] public void CanLoadFromWithinEventBatch() { var events = new List<EventData> { Event(0, "id2"), Event(1, "id2"), Event(2, "id2"), Event(0, "id1"), Event(1, "id1"), Event(2, "id1"), }; _eventStore.Save(Guid.NewGuid(), events); // assert var loadedEvents = _eventStore.Load("id1", 1).ToList(); Assert.That(loadedEvents.Count, Is.EqualTo(2)); Assert.That(loadedEvents[0].GetSequenceNumber(), Is.EqualTo(1)); Assert.That(loadedEvents[1].GetSequenceNumber(), Is.EqualTo(2)); } [Test] public void AssignsGlobalSequenceNumberToEvents() { var events = new List<EventData> { Event(0, "id1"), Event(0, "id2") }; _eventStore.Save(Guid.NewGuid(), events); // assert var loadedEvents = _eventStore.Stream().ToList(); Assert.That(events.Select(e => e.GetGlobalSequenceNumber()), Is.EqualTo(new[] { 0, 1 })); Assert.That(loadedEvents.Select(e => e.GetGlobalSequenceNumber()), Is.EqualTo(new[] { 0, 1 })); } [Test] public void BatchIdIsAppliedAsMetadataToEvents() { // arrange // act var batch1 = Guid.NewGuid(); var batch2 = Guid.NewGuid(); _eventStore.Save(batch1, new[] { Event(0, "id1"), Event(0, "id2") }); _eventStore.Save(batch2, new[] { Event(0, "id3"), Event(0, "id4"), Event(0, "id5") }); // assert var allEvents = _eventStore.Stream().ToList(); Assert.That(allEvents.Count, Is.EqualTo(5)); var batches = allEvents .GroupBy(e => e.GetBatchId()) .OrderBy(b => b.Count()) .ToList(); Assert.That(batches.Count, Is.EqualTo(2)); Assert.That(batches[0].Key, Is.EqualTo(batch1)); Assert.That(batches[1].Key, Is.EqualTo(batch2)); Assert.That(batches[0].Count(), Is.EqualTo(2)); Assert.That(batches[1].Count(), Is.EqualTo(3)); } [Test] public void EventAreAutomaticallyGivenGlobalSequenceNumbers() { // arrange // act _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "id1") }); _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "id2") }); _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "id3") }); _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "id4") }); _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "id5") }); // assert var allEvents = _eventStore .Stream() .Select(e => new { Event = e, GlobalSequenceNumber = e.GetGlobalSequenceNumber() }) .OrderBy(a => a.GlobalSequenceNumber) .ToList(); Assert.That(allEvents.Count, Is.EqualTo(5)); Assert.That(allEvents.Select(a => a.GlobalSequenceNumber), Is.EqualTo(new[] { 0, 1, 2, 3, 4 })); } [Test] public void CanSaveEventBatch() { // arrange var batchId = Guid.NewGuid(); var events = new[] { Event(1, "rootid") }; // act _eventStore.Save(batchId, events); // assert var persistedEvents = _eventStore.Load("rootid"); var someEvent = persistedEvents.Single(); var data = Encoding.UTF8.GetString(someEvent.Data); Assert.That(data, Is.EqualTo("hej")); } [Test] public void ValidatesPresenceOfSequenceNumbers() { // arrange var batchId = Guid.NewGuid(); var events = new[] { EventData.FromMetadata(new Metadata { {DomainEvent.MetadataKeys.AggregateRootId, Guid.NewGuid().ToString()}, //{DomainEvent.MetadataKeys.SequenceNumber, 1}, //< this one is missing! }, new byte[0]) }; // act // assert var ex = Assert.Throws<InvalidOperationException>(() => _eventStore.Save(batchId, events)); Console.WriteLine(ex); } [Test] public void ValidatesPresenceOfAggregateRootId() { // arrange var batchId = Guid.NewGuid(); var events = new[] { EventData.FromMetadata(new Metadata { //{DomainEvent.MetadataKeys.AggregateRootId, Guid.NewGuid()}, //< this one is missing! {DomainEvent.MetadataKeys.SequenceNumber, 1.ToString(Metadata.NumberCulture)}, }, new byte[0]) }; // act // assert var ex = Assert.Throws<InvalidOperationException>(() => _eventStore.Save(batchId, events)); Console.WriteLine(ex); } [Test] public void ValidatesSequenceOfSequenceNumbers() { // arrange var batchId = Guid.NewGuid(); var events = new[] { EventData.FromMetadata(new Metadata { {DomainEvent.MetadataKeys.SequenceNumber, 1.ToString(Metadata.NumberCulture)} }, new byte[0]), EventData.FromMetadata(new Metadata { {DomainEvent.MetadataKeys.SequenceNumber, 2.ToString(Metadata.NumberCulture)} }, new byte[0]), EventData.FromMetadata(new Metadata { {DomainEvent.MetadataKeys.SequenceNumber, 4.ToString(Metadata.NumberCulture)} }, new byte[0]) }; // act // assert var ex = Assert.Throws<InvalidOperationException>(() => _eventStore.Save(batchId, events)); Console.WriteLine(ex); } [Test] public void SavedSequenceNumbersAreUnique() { var events = new[] { Event(1, "id"), Event(2, "id"), Event(3, "id") }; _eventStore.Save(Guid.NewGuid(), events); var batchWithAlreadyUsedSequenceNumber = new[] { Event(2, "id") }; var ex = Assert.Throws<ConcurrencyException>(() => _eventStore.Save(Guid.NewGuid(), batchWithAlreadyUsedSequenceNumber)); Console.WriteLine(ex); } [Test] public void SavedSequenceNumbersAreUniqueScopedToAggregateRoot() { // arrange var events = new[] { Event(1, "id1"), Event(2, "id1"), Event(3, "id1") }; _eventStore.Save(Guid.NewGuid(), events); var batchWithAlreadyUsedSequenceNumberOnlyForAnotherAggregate = new[] { Event(1, "id2"), Event(2, "id2") }; // act // assert Assert.DoesNotThrow(() => _eventStore.Save(Guid.NewGuid(), batchWithAlreadyUsedSequenceNumberOnlyForAnotherAggregate)); var batchWithAlreadyUsedSequenceNumber = new[] { Event(4, "id1"), Event(2, "id2") }; var ex = Assert.Throws<ConcurrencyException>(() => _eventStore.Save(Guid.NewGuid(), batchWithAlreadyUsedSequenceNumber)); } [Test] public void CanLoadEvents() { // arrange _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "rootid"), Event(1, "rootid"), Event(2, "rootid"), Event(3, "rootid"), Event(4, "rootid"), Event(5, "rootid"), }); _eventStore.Save(Guid.NewGuid(), new[] { Event(6, "rootid"), Event(7, "rootid"), Event(8, "rootid"), Event(9, "rootid"), Event(10, "rootid"), Event(11, "rootid"), }); _eventStore.Save(Guid.NewGuid(), new[] { Event(12, "rootid"), Event(13, "rootid"), Event(14, "rootid"), }); // act // assert Assert.That(_eventStore.Load("rootid", 1).Take(1).Count(), Is.EqualTo(1)); Assert.That(_eventStore.Load("rootid", 1).Take(1).GetSeq().ToArray(), Is.EqualTo(Enumerable.Range(1, 1).ToArray())); Assert.That(_eventStore.Load("rootid", 1).Take(2).Count(), Is.EqualTo(2)); Assert.That(_eventStore.Load("rootid", 1).Take(2).GetSeq(), Is.EqualTo(Enumerable.Range(1, 2))); Assert.That(_eventStore.Load("rootid", 1).Take(10).Count(), Is.EqualTo(10)); Assert.That(_eventStore.Load("rootid", 1).Take(10).GetSeq(), Is.EqualTo(Enumerable.Range(1, 10))); Assert.That(_eventStore.Load("rootid", 4).Take(10).Count(), Is.EqualTo(10)); Assert.That(_eventStore.Load("rootid", 4).Take(10).GetSeq().ToArray(), Is.EqualTo(Enumerable.Range(4, 10).ToArray())); } [Test] public void CanLoadEventsByAggregateRootId() { // arrange _eventStore.Save(Guid.NewGuid(), new[] { Event(0, "agg1"), Event(1, "agg1"), Event(2, "agg2") }); _eventStore.Save(Guid.NewGuid(), new[] { Event(3, "agg1"), Event(4, "agg1"), Event(5, "agg2") }); // act var allEventsForAgg1 = _eventStore.Load("agg1").ToList(); var allEventsForAgg2 = _eventStore.Load("agg2").ToList(); // assert Assert.That(allEventsForAgg1.Count, Is.EqualTo(4)); Assert.That(allEventsForAgg1.GetSeq(), Is.EqualTo(new[] { 0, 1, 3, 4 })); Assert.That(allEventsForAgg2.Count, Is.EqualTo(2)); Assert.That(allEventsForAgg2.GetSeq(), Is.EqualTo(new[] { 2, 5 })); } [Test] public void SaveIsAtomic() { try { _eventStore.Save(Guid.NewGuid(), new[] { Event(1, "agg1"), Event(1, "agg2"), new ThrowingEvent { Meta = { {DomainEvent.MetadataKeys.SequenceNumber, 2.ToString(Metadata.NumberCulture)}, {DomainEvent.MetadataKeys.AggregateRootId, "agg2"} } } }); } catch { // ignore it! } Assert.AreEqual(0, _eventStore.Stream().Count()); Assert.AreEqual(0, _eventStore.Load("agg1").Count()); Assert.AreEqual(0, _eventStore.Load("agg2").Count()); } [TestCase(0)] [TestCase(1)] [TestCase(10)] public void CanGetNextGlobalSequenceNumber(int numberOfEvents) { for (var i = 0; i < numberOfEvents; i++) { _eventStore.Save(Guid.NewGuid(), new[] { Event(1, string.Format("id{0}", i)), }); } var nextGlobalSequenceNumber = _eventStore.GetNextGlobalSequenceNumber(); Assert.AreEqual(numberOfEvents, nextGlobalSequenceNumber); } [Test] public void LoadingFromEmptyStreamDoesNotFail() { Assert.AreEqual(0, _eventStore.Stream().Count()); Assert.AreEqual(0, _eventStore.Load("someid").Count()); } [TestCase(100, 3)] [TestCase(1000, 10, Ignore = TestCategories.IgnoreLongRunning)] [TestCase(10000, 10, Ignore = TestCategories.IgnoreLongRunning)] [TestCase(1000, 100, Ignore = TestCategories.IgnoreLongRunning)] [TestCase(1000, 1000, Ignore = TestCategories.IgnoreLongRunning)] public void CompareSavePerformance(int numberOfBatches, int numberOfEventsPerBatch) { CirqusLoggerFactory.Current = new NullLoggerFactory(); TakeTime(string.Format("Save {0} batches with {1} events in each", numberOfBatches, numberOfEventsPerBatch), () => { var seqNo = 0; numberOfBatches.Times(() => { var events = Enumerable .Range(0, numberOfEventsPerBatch) .Select(i => Event(seqNo++, "id")) .ToList(); _eventStore.Save(Guid.NewGuid(), events); }); }); } [TestCase(1000)] [TestCase(10000, Ignore = TestCategories.IgnoreLongRunning)] public void CompareLoadPerformance(int numberOfEvents) { CirqusLoggerFactory.Current = new NullLoggerFactory(); var seqNo = 0; _eventStore.Save(Guid.NewGuid(), Enumerable.Range(0, numberOfEvents).Select(i => Event(seqNo++, "rootid"))); TakeTime( string.Format("First time read stream of {0} events", numberOfEvents), () => _eventStore.Load("rootid").ToList()); TakeTime( string.Format("Second time read stream of {0} events", numberOfEvents), () => _eventStore.Load("rootid").ToList()); } [TestCase(1000)] [TestCase(10000, Ignore = TestCategories.IgnoreLongRunning)] [TestCase(100000, Ignore = TestCategories.IgnoreLongRunning)] public void CompareStreamPerformance(int numberOfEvents) { CirqusLoggerFactory.Current = new NullLoggerFactory(); var seqNo = 0; _eventStore.Save(Guid.NewGuid(), Enumerable.Range(0, numberOfEvents).Select(i => Event(seqNo++, "rootid"))); TakeTime( string.Format("Read stream of {0} events", numberOfEvents), () => _eventStore.Stream().ToList()); } [Test] public void TimeStampsCanRoundtripAsTheyShould() { var someLocalTime = new DateTime(2015, 10, 31, 12, 10, 15, DateTimeKind.Local); var someUtcTime = someLocalTime.ToUniversalTime(); TimeMachine.FixCurrentTimeTo(someUtcTime); var serializer = new JsonDomainEventSerializer(); var processor = CommandProcessor.With() .EventStore(e => e.RegisterInstance(_eventStore)) .EventDispatcher(e => e.UseConsoleOutEventDispatcher()) .Options(o => o.RegisterInstance<IDomainEventSerializer>(serializer)) .Create(); RegisterForDisposal(processor); processor.ProcessCommand(new MakeSomeRootEmitTheEvent("rootid")); var domainEvents = _eventStore.Stream().Select(serializer.Deserialize).Single(); Assert.That(domainEvents.GetUtcTime(), Is.EqualTo(someUtcTime)); } static EventData Event(int seq, string aggregateRootId) { return EventData.FromMetadata(new Metadata { {DomainEvent.MetadataKeys.SequenceNumber, seq.ToString(Metadata.NumberCulture)}, {DomainEvent.MetadataKeys.AggregateRootId, aggregateRootId} }, Encoding.UTF8.GetBytes("hej")); } public class MakeSomeRootEmitTheEvent : Command<SomeRoot> { public MakeSomeRootEmitTheEvent(string aggregateRootId) : base(aggregateRootId) { } public override void Execute(SomeRoot aggregateRoot) { aggregateRoot.EmitTheEvent(); } } public class SomeRoot : AggregateRoot, IEmit<SomeRootEvent> { public void EmitTheEvent() { Emit(new SomeRootEvent()); } public void Apply(SomeRootEvent e) { } } public class SomeRootEvent : DomainEvent<SomeRoot> { } class ThrowingEvent : EventData { public ThrowingEvent() : base(null, null) { } public override byte[] Data { get { throw new Exception("I ruin your batch!"); } } } } }
using UnityEditor; using UnityEditor.IMGUI.Controls; using System.Collections.Generic; using System.IO; using UnityEngine.AssetBundles.AssetBundleDataSource; namespace UnityEngine.AssetBundles { [System.Serializable] public class AssetBundleBuildTab { const string k_BuildPrefPrefix = "ABBBuild:"; // gui vars [SerializeField] private ValidBuildTarget m_BuildTarget = ValidBuildTarget.StandaloneWindows; [SerializeField] private CompressOptions m_Compression = CompressOptions.StandardCompression; private string m_OutputPath = string.Empty; [SerializeField] private bool m_UseDefaultPath = true; private string m_streamingPath = "Assets/StreamingAssets"; [SerializeField] private bool m_AdvancedSettings; [SerializeField] private Vector2 m_ScrollPosition; class ToggleData { public ToggleData(bool s, string title, string tooltip, List<string> onToggles, BuildAssetBundleOptions opt = BuildAssetBundleOptions.None) { if (onToggles.Contains(title)) state = true; else state = s; content = new GUIContent(title, tooltip); option = opt; } //public string prefsKey //{ get { return k_BuildPrefPrefix + content.text; } } public bool state; public GUIContent content; public BuildAssetBundleOptions option; } [SerializeField] private List<string> m_OnToggles; List<ToggleData> m_ToggleData; ToggleData m_ForceRebuild; ToggleData m_CopyToStreaming; GUIContent m_TargetContent; GUIContent m_CompressionContent; public enum CompressOptions { Uncompressed = 0, StandardCompression, ChunkBasedCompression, } GUIContent[] m_CompressionOptions = { new GUIContent("No Compression"), new GUIContent("Standard Compression (LZMA)"), new GUIContent("Chunk Based Compression (LZ4)") }; int[] m_CompressionValues = { 0, 1, 2 }; public AssetBundleBuildTab() { m_AdvancedSettings = false; m_OnToggles = new List<string>(); m_UseDefaultPath = true; } public void OnEnable(Rect pos, EditorWindow parent) { m_ToggleData = new List<ToggleData>(); m_ToggleData.Add(new ToggleData( false, "Exclude Type Information", "Do not include type information within the asset bundle (don't write type tree).", m_OnToggles, BuildAssetBundleOptions.DisableWriteTypeTree)); m_ToggleData.Add(new ToggleData( false, "Force Rebuild", "Force rebuild the asset bundles", m_OnToggles, BuildAssetBundleOptions.ForceRebuildAssetBundle)); m_ToggleData.Add(new ToggleData( false, "Ignore Type Tree Changes", "Ignore the type tree changes when doing the incremental build check.", m_OnToggles, BuildAssetBundleOptions.IgnoreTypeTreeChanges)); m_ToggleData.Add(new ToggleData( false, "Append Hash", "Append the hash to the assetBundle name.", m_OnToggles, BuildAssetBundleOptions.AppendHashToAssetBundleName)); m_ToggleData.Add(new ToggleData( false, "Strict Mode", "Do not allow the build to succeed if any errors are reporting during it.", m_OnToggles, BuildAssetBundleOptions.StrictMode)); m_ToggleData.Add(new ToggleData( false, "Dry Run Build", "Do a dry run build.", m_OnToggles, BuildAssetBundleOptions.DryRunBuild)); m_ForceRebuild = new ToggleData( false, "Clear Folders", "Will wipe out all contents of build directory as well as StreamingAssets/AssetBundles if you are choosing to copy build there.", m_OnToggles); m_CopyToStreaming = new ToggleData( false, "Copy to StreamingAssets", "After build completes, will copy all build content to " + m_streamingPath + " for use in stand-alone player.", m_OnToggles); m_TargetContent = new GUIContent("Build Target", "Choose target platform to build for."); m_CompressionContent = new GUIContent("Compression", "Choose no compress, standard (LZMA), or chunk based (LZ4)"); if(m_UseDefaultPath) { ResetPathToDefault(); } } public void OnGUI(Rect pos) { m_ScrollPosition = EditorGUILayout.BeginScrollView(m_ScrollPosition); bool newState = false; //basic options EditorGUILayout.Space(); GUILayout.BeginVertical(); // build target using (new EditorGUI.DisabledScope (!AssetBundleModel.Model.DataSource.CanSpecifyBuildTarget)) { ValidBuildTarget tgt = (ValidBuildTarget)EditorGUILayout.EnumPopup(m_TargetContent, m_BuildTarget); if (tgt != m_BuildTarget) { m_BuildTarget = tgt; if(m_UseDefaultPath) { m_OutputPath = "AssetBundles/"; m_OutputPath += m_BuildTarget.ToString(); EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_OutputPath); } } } ////output path using (new EditorGUI.DisabledScope (!AssetBundleModel.Model.DataSource.CanSpecifyBuildOutputDirectory)) { EditorGUILayout.Space(); GUILayout.BeginHorizontal(); var newPath = EditorGUILayout.TextField("Output Path", m_OutputPath); if (newPath != m_OutputPath) { m_UseDefaultPath = false; m_OutputPath = newPath; EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_OutputPath); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Browse", GUILayout.MaxWidth(75f))) BrowseForFolder(); if (GUILayout.Button("Reset", GUILayout.MaxWidth(75f))) ResetPathToDefault(); if (string.IsNullOrEmpty(m_OutputPath)) m_OutputPath = EditorUserBuildSettings.GetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath"); GUILayout.EndHorizontal(); EditorGUILayout.Space(); newState = GUILayout.Toggle( m_ForceRebuild.state, m_ForceRebuild.content); if (newState != m_ForceRebuild.state) { if (newState) m_OnToggles.Add(m_ForceRebuild.content.text); else m_OnToggles.Remove(m_ForceRebuild.content.text); m_ForceRebuild.state = newState; } newState = GUILayout.Toggle( m_CopyToStreaming.state, m_CopyToStreaming.content); if (newState != m_CopyToStreaming.state) { if (newState) m_OnToggles.Add(m_CopyToStreaming.content.text); else m_OnToggles.Remove(m_CopyToStreaming.content.text); m_CopyToStreaming.state = newState; } } // advanced options using (new EditorGUI.DisabledScope (!AssetBundleModel.Model.DataSource.CanSpecifyBuildOptions)) { EditorGUILayout.Space(); m_AdvancedSettings = EditorGUILayout.Foldout(m_AdvancedSettings, "Advanced Settings"); if(m_AdvancedSettings) { var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 1; CompressOptions cmp = (CompressOptions)EditorGUILayout.IntPopup( m_CompressionContent, (int)m_Compression, m_CompressionOptions, m_CompressionValues); if (cmp != m_Compression) { m_Compression = cmp; } foreach (var tog in m_ToggleData) { newState = EditorGUILayout.ToggleLeft( tog.content, tog.state); if (newState != tog.state) { if (newState) m_OnToggles.Add(tog.content.text); else m_OnToggles.Remove(tog.content.text); tog.state = newState; } } EditorGUILayout.Space(); EditorGUI.indentLevel = indent; } } // build. EditorGUILayout.Space(); if (GUILayout.Button("Build") ) { ExecuteBuild(); } GUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } private void ExecuteBuild() { if (AssetBundleModel.Model.DataSource.CanSpecifyBuildOutputDirectory) { if (string.IsNullOrEmpty(m_OutputPath)) BrowseForFolder(); if (string.IsNullOrEmpty(m_OutputPath)) //in case they hit "cancel" on the open browser { Debug.LogError("AssetBundle Build: No valid output path for build."); return; } if (m_ForceRebuild.state) { string message = "Do you want to delete all files in the directory " + m_OutputPath; if (m_CopyToStreaming.state) message += " and " + m_streamingPath; message += "?"; if (EditorUtility.DisplayDialog("File delete confirmation", message, "Yes", "No")) { try { if (Directory.Exists(m_OutputPath)) Directory.Delete(m_OutputPath, true); if (m_CopyToStreaming.state) if (Directory.Exists(m_streamingPath)) Directory.Delete(m_streamingPath, true); } catch (System.Exception e) { Debug.LogException(e); } } } if (!Directory.Exists(m_OutputPath)) Directory.CreateDirectory(m_OutputPath); } BuildAssetBundleOptions opt = BuildAssetBundleOptions.None; if (AssetBundleModel.Model.DataSource.CanSpecifyBuildOptions) { if (m_Compression == CompressOptions.Uncompressed) opt |= BuildAssetBundleOptions.UncompressedAssetBundle; else if (m_Compression == CompressOptions.ChunkBasedCompression) opt |= BuildAssetBundleOptions.ChunkBasedCompression; foreach (var tog in m_ToggleData) { if (tog.state) opt |= tog.option; } } ABBuildInfo buildInfo = new ABBuildInfo(); buildInfo.outputDirectory = m_OutputPath; buildInfo.options = opt; buildInfo.buildTarget = (BuildTarget)m_BuildTarget; AssetBundleModel.Model.DataSource.BuildAssetBundles (buildInfo); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); if(m_CopyToStreaming.state) DirectoryCopy(m_OutputPath, m_streamingPath); } private static void DirectoryCopy(string sourceDirName, string destDirName) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath); } } private void BrowseForFolder() { m_UseDefaultPath = false; var newPath = EditorUtility.OpenFolderPanel("Bundle Folder", m_OutputPath, string.Empty); if (!string.IsNullOrEmpty(newPath)) { var gamePath = System.IO.Path.GetFullPath("."); gamePath = gamePath.Replace("\\", "/"); if (newPath.StartsWith(gamePath) && newPath.Length > gamePath.Length) newPath = newPath.Remove(0, gamePath.Length+1); m_OutputPath = newPath; EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_OutputPath); } } private void ResetPathToDefault() { m_UseDefaultPath = true; m_OutputPath = "AssetBundles/"; m_OutputPath += m_BuildTarget.ToString(); EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_OutputPath); } //Note: this is the provided BuildTarget enum with some entries removed as they are invalid in the dropdown public enum ValidBuildTarget { //NoTarget = -2, --doesn't make sense //iPhone = -1, --deprecated //BB10 = -1, --deprecated //MetroPlayer = -1, --deprecated StandaloneOSXUniversal = 2, StandaloneOSXIntel = 4, StandaloneWindows = 5, WebPlayer = 6, WebPlayerStreamed = 7, iOS = 9, PS3 = 10, XBOX360 = 11, Android = 13, StandaloneLinux = 17, StandaloneWindows64 = 19, WebGL = 20, WSAPlayer = 21, StandaloneLinux64 = 24, StandaloneLinuxUniversal = 25, WP8Player = 26, StandaloneOSXIntel64 = 27, BlackBerry = 28, Tizen = 29, PSP2 = 30, PS4 = 31, PSM = 32, XboxOne = 33, SamsungTV = 34, N3DS = 35, WiiU = 36, tvOS = 37, Switch = 38 } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // HashRepartitionEnumerator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics.Contracts; namespace System.Linq.Parallel { /// <summary> /// This enumerator handles the actual coordination among partitions required to /// accomplish the repartitioning operation, as explained above. /// </summary> /// <typeparam name="TInputOutput">The kind of elements.</typeparam> /// <typeparam name="THashKey">The key used to distribute elements.</typeparam> /// <typeparam name="TIgnoreKey">The kind of keys found in the source (ignored).</typeparam> internal class HashRepartitionEnumerator<TInputOutput, THashKey, TIgnoreKey> : QueryOperatorEnumerator<Pair, int> { private const int ENUMERATION_NOT_STARTED = -1; // Sentinel to note we haven't begun enumerating yet. private readonly int _partitionCount; // The number of partitions. private readonly int _partitionIndex; // Our unique partition index. private readonly Func<TInputOutput, THashKey> _keySelector; // A key-selector function. private readonly HashRepartitionStream<TInputOutput, THashKey, int> _repartitionStream; // A repartitioning stream. private readonly ListChunk<Pair>[][] _valueExchangeMatrix; // Matrix to do inter-task communication. private readonly QueryOperatorEnumerator<TInputOutput, TIgnoreKey> _source; // The immediate source of data. private CountdownEvent _barrier; // Used to signal and wait for repartitions to complete. private readonly CancellationToken _cancellationToken; // A token for canceling the process. private Mutables _mutables; // Mutable fields for this enumerator. class Mutables { internal int _currentBufferIndex; // Current buffer index. internal ListChunk<Pair> _currentBuffer; // The buffer we're currently enumerating. internal int _currentIndex; // Current index into the buffer. internal Mutables() { _currentBufferIndex = ENUMERATION_NOT_STARTED; } } //--------------------------------------------------------------------------------------- // Creates a new repartitioning enumerator. // // Arguments: // source - the data stream from which to pull elements // useOrdinalOrderPreservation - whether order preservation is required // partitionCount - total number of partitions // partitionIndex - this operator's unique partition index // repartitionStream - the stream object to use for partition selection // barrier - a latch used to signal task completion // buffers - a set of buffers for inter-task communication // internal HashRepartitionEnumerator( QueryOperatorEnumerator<TInputOutput, TIgnoreKey> source, int partitionCount, int partitionIndex, Func<TInputOutput, THashKey> keySelector, HashRepartitionStream<TInputOutput, THashKey, int> repartitionStream, CountdownEvent barrier, ListChunk<Pair>[][] valueExchangeMatrix, CancellationToken cancellationToken) { Contract.Assert(source != null); Contract.Assert(keySelector != null || typeof(THashKey) == typeof(NoKeyMemoizationRequired)); Contract.Assert(repartitionStream != null); Contract.Assert(barrier != null); Contract.Assert(valueExchangeMatrix != null); Contract.Assert(valueExchangeMatrix.GetLength(0) == partitionCount, "expected square matrix of buffers (NxN)"); Contract.Assert(partitionCount > 0 && valueExchangeMatrix[0].Length == partitionCount, "expected square matrix of buffers (NxN)"); Contract.Assert(0 <= partitionIndex && partitionIndex < partitionCount); _source = source; _partitionCount = partitionCount; _partitionIndex = partitionIndex; _keySelector = keySelector; _repartitionStream = repartitionStream; _barrier = barrier; _valueExchangeMatrix = valueExchangeMatrix; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Retrieves the next element from this partition. All repartitioning operators across // all partitions cooperate in a barrier-style algorithm. The first time an element is // requested, the repartitioning operator will enter the 1st phase: during this phase, it // scans its entire input and compute the destination partition for each element. During // the 2nd phase, each partition scans the elements found by all other partitions for // it, and yield this to callers. The only synchronization required is the barrier itself // -- all other parts of this algorithm are synchronization-free. // // Notes: One rather large penalty that this algorithm incurs is higher memory usage and a // larger time-to-first-element latency, at least compared with our old implementation; this // happens because all input elements must be fetched before we can produce a single output // element. In many cases this isn't too terrible: e.g. a GroupBy requires this to occur // anyway, so having the repartitioning operator do so isn't complicating matters much at all. // internal override bool MoveNext(ref Pair currentElement, ref int currentKey) { if (_partitionCount == 1) { // If there's only one partition, no need to do any sort of exchanges. TIgnoreKey keyUnused = default(TIgnoreKey); TInputOutput current = default(TInputOutput); #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif if (_source.MoveNext(ref current, ref keyUnused)) { currentElement = new Pair( current, _keySelector == null ? default(THashKey) : _keySelector(current)); return true; } return false; } Mutables mutables = _mutables; if (mutables == null) mutables = _mutables = new Mutables(); // If we haven't enumerated the source yet, do that now. This is the first phase // of a two-phase barrier style operation. if (mutables._currentBufferIndex == ENUMERATION_NOT_STARTED) { EnumerateAndRedistributeElements(); Contract.Assert(mutables._currentBufferIndex != ENUMERATION_NOT_STARTED); } // Once we've enumerated our contents, we can then go back and walk the buffers that belong // to the current partition. This is phase two. Note that we slyly move on to the first step // of phase two before actually waiting for other partitions. That's because we can enumerate // the buffer we wrote to above, as already noted. while (mutables._currentBufferIndex < _partitionCount) { // If the queue is non-null and still has elements, yield them. if (mutables._currentBuffer != null) { if (++mutables._currentIndex < mutables._currentBuffer.Count) { // Return the current element. currentElement = mutables._currentBuffer._chunk[mutables._currentIndex]; return true; } else { // If the chunk is empty, advance to the next one (if any). mutables._currentIndex = ENUMERATION_NOT_STARTED; mutables._currentBuffer = mutables._currentBuffer.Next; Contract.Assert(mutables._currentBuffer == null || mutables._currentBuffer.Count > 0); continue; // Go back around and invoke this same logic. } } // We're done with the current partition. Slightly different logic depending on whether // we're on our own buffer or one that somebody else found for us. if (mutables._currentBufferIndex == _partitionIndex) { // We now need to wait at the barrier, in case some other threads aren't done. // Once we wake up, we reset our index and will increment it immediately after. _barrier.Wait(_cancellationToken); mutables._currentBufferIndex = ENUMERATION_NOT_STARTED; } // Advance to the next buffer. mutables._currentBufferIndex++; mutables._currentIndex = ENUMERATION_NOT_STARTED; if (mutables._currentBufferIndex == _partitionIndex) { // Skip our current buffer (since we already enumerated it). mutables._currentBufferIndex++; } // Assuming we're within bounds, retrieve the next buffer object. if (mutables._currentBufferIndex < _partitionCount) { mutables._currentBuffer = _valueExchangeMatrix[mutables._currentBufferIndex][_partitionIndex]; } } // We're done. No more buffers to enumerate. return false; } //--------------------------------------------------------------------------------------- // Called when this enumerator is first enumerated; it must walk through the source // and redistribute elements to their slot in the exchange matrix. // private void EnumerateAndRedistributeElements() { Mutables mutables = _mutables; Contract.Assert(mutables != null); ListChunk<Pair>[] privateBuffers = new ListChunk<Pair>[_partitionCount]; TInputOutput element = default(TInputOutput); TIgnoreKey ignoreKey = default(TIgnoreKey); int loopCount = 0; while (_source.MoveNext(ref element, ref ignoreKey)) { if ((loopCount++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // Calculate the element's destination partition index, placing it into the // appropriate buffer from which partitions will later enumerate. int destinationIndex; THashKey elementHashKey = default(THashKey); if (_keySelector != null) { elementHashKey = _keySelector(element); destinationIndex = _repartitionStream.GetHashCode(elementHashKey) % _partitionCount; } else { Contract.Assert(typeof(THashKey) == typeof(NoKeyMemoizationRequired)); destinationIndex = _repartitionStream.GetHashCode(element) % _partitionCount; } Contract.Assert(0 <= destinationIndex && destinationIndex < _partitionCount, "destination partition outside of the legal range of partitions"); // Get the buffer for the destnation partition, lazily allocating if needed. We maintain // this list in our own private cache so that we avoid accessing shared memory locations // too much. In the original implementation, we'd access the buffer in the matrix ([N,M], // where N is the current partition and M is the destination), but some rudimentary // performance profiling indicates copying at the end performs better. ListChunk<Pair> buffer = privateBuffers[destinationIndex]; if (buffer == null) { const int INITIAL_PRIVATE_BUFFER_SIZE = 128; privateBuffers[destinationIndex] = buffer = new ListChunk<Pair>(INITIAL_PRIVATE_BUFFER_SIZE); } buffer.Add(new Pair(element, elementHashKey)); } // Copy the local buffers to the shared space and then signal to other threads that // we are done. We can then immediately move on to enumerating the elements we found // for the current partition before waiting at the barrier. If we found a lot, we will // hopefully never have to physically wait. for (int i = 0; i < _partitionCount; i++) { _valueExchangeMatrix[_partitionIndex][i] = privateBuffers[i]; } _barrier.Signal(); // Begin at our own buffer. mutables._currentBufferIndex = _partitionIndex; mutables._currentBuffer = privateBuffers[_partitionIndex]; mutables._currentIndex = ENUMERATION_NOT_STARTED; } protected override void Dispose(bool disposed) { if (_barrier != null) { // Since this enumerator is being disposed, we will decrement the barrier, // in case other enumerators will wait on the barrier. if (_mutables == null || (_mutables._currentBufferIndex == ENUMERATION_NOT_STARTED)) { _barrier.Signal(); _barrier = null; } _source.Dispose(); } } } }
#region File Description //----------------------------------------------------------------------------- // StatisticsRange.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Text; using Microsoft.Xna.Framework.Content; #endregion namespace RolePlayingGameData { /// <summary> /// A range of character statistics values. /// </summary> /// <remarks>Typically used for constrained random modifiers.</remarks> #if WINDOWS [Serializable] #endif public class StatisticsRange { [ContentSerializer(Optional = true)] public Int32Range HealthPointsRange; [ContentSerializer(Optional = true)] public Int32Range MagicPointsRange; [ContentSerializer(Optional = true)] public Int32Range PhysicalOffenseRange; [ContentSerializer(Optional = true)] public Int32Range PhysicalDefenseRange; [ContentSerializer(Optional = true)] public Int32Range MagicalOffenseRange; [ContentSerializer(Optional = true)] public Int32Range MagicalDefenseRange; #region Value Generation /// <summary> /// Generate a random value between the minimum and maximum, inclusively. /// </summary> /// <param name="random">The Random object used to generate the value.</param> public StatisticsValue GenerateValue(Random random) { // check the parameters Random usedRandom = random; if (usedRandom == null) { usedRandom = new Random(); } // generate the new value StatisticsValue outputValue = new StatisticsValue(); outputValue.HealthPoints = HealthPointsRange.GenerateValue(usedRandom); outputValue.MagicPoints = MagicPointsRange.GenerateValue(usedRandom); outputValue.PhysicalOffense = PhysicalOffenseRange.GenerateValue(usedRandom); outputValue.PhysicalDefense = PhysicalDefenseRange.GenerateValue(usedRandom); outputValue.MagicalOffense = MagicalOffenseRange.GenerateValue(usedRandom); outputValue.MagicalDefense = MagicalDefenseRange.GenerateValue(usedRandom); return outputValue; } #endregion #region String Output /// <summary> /// Builds a string that describes this object. /// </summary> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("HP:"); sb.Append(HealthPointsRange.ToString()); sb.Append("; MP:"); sb.Append(MagicPointsRange.ToString()); sb.Append("; PO:"); sb.Append(PhysicalOffenseRange.ToString()); sb.Append("; PD:"); sb.Append(PhysicalDefenseRange.ToString()); sb.Append("; MO:"); sb.Append(MagicalOffenseRange.ToString()); sb.Append("; MD:"); sb.Append(MagicalDefenseRange.ToString()); return sb.ToString(); } /// <summary> /// Builds a string that describes a modifier, where non-zero stats are skipped. /// </summary> public string GetModifierString() { StringBuilder sb = new StringBuilder(); bool firstStatistic = true; // add the health points value, if any if ((HealthPointsRange.Minimum != 0) || (HealthPointsRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("HP:"); sb.Append(HealthPointsRange.ToString()); } // add the magic points value, if any if ((MagicPointsRange.Minimum != 0) || (MagicPointsRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MP:"); sb.Append(MagicPointsRange.ToString()); } // add the physical offense value, if any if ((PhysicalOffenseRange.Minimum != 0) || (PhysicalOffenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("PO:"); sb.Append(PhysicalOffenseRange.ToString()); } // add the physical defense value, if any if ((PhysicalDefenseRange.Minimum != 0) || (PhysicalDefenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("PD:"); sb.Append(PhysicalDefenseRange.ToString()); } // add the magical offense value, if any if ((MagicalOffenseRange.Minimum != 0) || (MagicalOffenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MO:"); sb.Append(MagicalOffenseRange.ToString()); } // add the magical defense value, if any if ((MagicalDefenseRange.Minimum != 0) || (MagicalDefenseRange.Maximum != 0)) { if (firstStatistic) { firstStatistic = false; } else { sb.Append("; "); } sb.Append("MD:"); sb.Append(MagicalDefenseRange.ToString()); } return sb.ToString(); } #endregion #region Operator: StatisticsRange + StatisticsValue /// <summary> /// Add one value to another, piecewise, and return the result. /// </summary> public static StatisticsRange Add(StatisticsRange value1, StatisticsValue value2) { StatisticsRange outputRange = new StatisticsRange(); outputRange.HealthPointsRange = value1.HealthPointsRange + value2.HealthPoints; outputRange.MagicPointsRange = value1.MagicPointsRange + value2.MagicPoints; outputRange.PhysicalOffenseRange = value1.PhysicalOffenseRange + value2.PhysicalOffense; outputRange.PhysicalDefenseRange = value1.PhysicalDefenseRange + value2.PhysicalDefense; outputRange.MagicalOffenseRange = value1.MagicalOffenseRange + value2.MagicalOffense; outputRange.MagicalDefenseRange = value1.MagicalDefenseRange + value2.MagicalDefense; return outputRange; } /// <summary> /// Add one value to another, piecewise, and return the result. /// </summary> public static StatisticsRange operator +(StatisticsRange value1, StatisticsValue value2) { return Add(value1, value2); } #endregion #region Content Type Reader /// <summary> /// Reads a StatisticsRange object from the content pipeline. /// </summary> public class StatisticsRangeReader : ContentTypeReader<StatisticsRange> { protected override StatisticsRange Read(ContentReader input, StatisticsRange existingInstance) { StatisticsRange output = new StatisticsRange(); output.HealthPointsRange = input.ReadObject<Int32Range>(); output.MagicPointsRange = input.ReadObject<Int32Range>(); output.PhysicalOffenseRange = input.ReadObject<Int32Range>(); output.PhysicalDefenseRange = input.ReadObject<Int32Range>(); output.MagicalOffenseRange = input.ReadObject<Int32Range>(); output.MagicalDefenseRange = input.ReadObject<Int32Range>(); return output; } } #endregion } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Class representing a V8 value handle. V8 handles can only be accessed from /// the thread on which they are created. Valid threads for creating a V8 handle /// include the render process main thread (TID_RENDERER) and WebWorker threads. /// A task runner for posting tasks on the associated thread can be retrieved via /// the CefV8Context::GetTaskRunner() method. /// </summary> public sealed unsafe partial class CefV8Value { /// <summary> /// Create a new CefV8Value object of type undefined. /// </summary> public static CefV8Value CreateUndefined() { return CefV8Value.FromNative( cef_v8value_t.create_undefined() ); } /// <summary> /// Create a new CefV8Value object of type null. /// </summary> public static CefV8Value CreateNull() { return CefV8Value.FromNative( cef_v8value_t.create_null() ); } /// <summary> /// Create a new CefV8Value object of type bool. /// </summary> public static CefV8Value CreateBool(bool value) { return CefV8Value.FromNative( cef_v8value_t.create_bool(value ? 1 : 0) ); } /// <summary> /// Create a new CefV8Value object of type int. /// </summary> public static CefV8Value CreateInt(int value) { return CefV8Value.FromNative( cef_v8value_t.create_int(value) ); } /// <summary> /// Create a new CefV8Value object of type unsigned int. /// </summary> public static CefV8Value CreateUInt(uint value) { return CefV8Value.FromNative( cef_v8value_t.create_uint(value) ); } /// <summary> /// Create a new CefV8Value object of type double. /// </summary> public static CefV8Value CreateDouble(double value) { return CefV8Value.FromNative( cef_v8value_t.create_double(value) ); } /// <summary> /// Create a new CefV8Value object of type Date. This method should only be /// called from within the scope of a CefV8ContextHandler, CefV8Handler or /// CefV8Accessor callback, or in combination with calling Enter() and Exit() /// on a stored CefV8Context reference. /// </summary> public static CefV8Value CreateDate(DateTime value) { var n_value = new cef_time_t(value); return CefV8Value.FromNative( cef_v8value_t.create_date(&n_value) ); } /// <summary> /// Create a new CefV8Value object of type string. /// </summary> public static CefV8Value CreateString(string value) { fixed (char* value_str = value) { var n_value = new cef_string_t(value_str, value != null ? value.Length : 0); return CefV8Value.FromNative( cef_v8value_t.create_string(&n_value) ); } } /// <summary> /// Create a new CefV8Value object of type object with optional accessor. This /// method should only be called from within the scope of a /// CefV8ContextHandler, CefV8Handler or CefV8Accessor callback, or in /// combination with calling Enter() and Exit() on a stored CefV8Context /// reference. /// </summary> public static CefV8Value CreateObject(CefV8Accessor accessor) { return CefV8Value.FromNative( cef_v8value_t.create_object(accessor != null ? accessor.ToNative() : null) ); } /// <summary> /// Create a new CefV8Value object of type array with the specified |length|. /// If |length| is negative the returned array will have length 0. This method /// should only be called from within the scope of a CefV8ContextHandler, /// CefV8Handler or CefV8Accessor callback, or in combination with calling /// Enter() and Exit() on a stored CefV8Context reference. /// </summary> public static CefV8Value CreateArray(int length) { return CefV8Value.FromNative( cef_v8value_t.create_array(length) ); } /// <summary> /// Create a new CefV8Value object of type function. This method should only be /// called from within the scope of a CefV8ContextHandler, CefV8Handler or /// CefV8Accessor callback, or in combination with calling Enter() and Exit() /// on a stored CefV8Context reference. /// </summary> public static CefV8Value CreateFunction(string name, CefV8Handler handler) { fixed (char* name_str = name) { var n_name = new cef_string_t(name_str, name != null ? name.Length : 0); return CefV8Value.FromNative( cef_v8value_t.create_function(&n_name, handler.ToNative()) ); } } /// <summary> /// Returns true if the underlying handle is valid and it can be accessed on /// the current thread. Do not call any other methods if this method returns /// false. /// </summary> public bool IsValid { get { return cef_v8value_t.is_valid(_self) != 0; } } /// <summary> /// True if the value type is undefined. /// </summary> public bool IsUndefined { get { return cef_v8value_t.is_undefined(_self) != 0; } } /// <summary> /// True if the value type is null. /// </summary> public bool IsNull { get { return cef_v8value_t.is_null(_self) != 0; } } /// <summary> /// True if the value type is bool. /// </summary> public bool IsBool { get { return cef_v8value_t.is_bool(_self) != 0; } } /// <summary> /// True if the value type is int. /// </summary> public bool IsInt { get { return cef_v8value_t.is_int(_self) != 0; } } /// <summary> /// True if the value type is unsigned int. /// </summary> public bool IsUInt { get { return cef_v8value_t.is_uint(_self) != 0; } } /// <summary> /// True if the value type is double. /// </summary> public bool IsDouble { get { return cef_v8value_t.is_double(_self) != 0; } } /// <summary> /// True if the value type is Date. /// </summary> public bool IsDate { get { return cef_v8value_t.is_date(_self) != 0; } } /// <summary> /// True if the value type is string. /// </summary> public bool IsString { get { return cef_v8value_t.is_string(_self) != 0; } } /// <summary> /// True if the value type is object. /// </summary> public bool IsObject { get { return cef_v8value_t.is_object(_self) != 0; } } /// <summary> /// True if the value type is array. /// </summary> public bool IsArray { get { return cef_v8value_t.is_array(_self) != 0; } } /// <summary> /// True if the value type is function. /// </summary> public bool IsFunction { get { return cef_v8value_t.is_function(_self) != 0; } } /// <summary> /// Returns true if this object is pointing to the same handle as |that| /// object. /// </summary> public bool IsSame(CefV8Value that) { if (that == null) return false; return cef_v8value_t.is_same(_self, that.ToNative()) != 0; } /// <summary> /// Return a bool value. The underlying data will be converted to if /// necessary. /// </summary> public bool GetBoolValue() { return cef_v8value_t.get_bool_value(_self) != 0; } /// <summary> /// Return an int value. The underlying data will be converted to if /// necessary. /// </summary> public int GetIntValue() { return cef_v8value_t.get_int_value(_self); } /// <summary> /// Return an unisgned int value. The underlying data will be converted to if /// necessary. /// </summary> public uint GetUIntValue() { return cef_v8value_t.get_uint_value(_self); } /// <summary> /// Return a double value. The underlying data will be converted to if /// necessary. /// </summary> public double GetDoubleValue() { return cef_v8value_t.get_double_value(_self); } /// <summary> /// Return a Date value. The underlying data will be converted to if /// necessary. /// </summary> public DateTime GetDateValue() { var value = cef_v8value_t.get_date_value(_self); return cef_time_t.ToDateTime(&value); } /// <summary> /// Return a string value. The underlying data will be converted to if /// necessary. /// </summary> public string GetStringValue() { var n_result = cef_v8value_t.get_string_value(_self); return cef_string_userfree.ToString(n_result); } /// <summary> /// OBJECT METHODS - These methods are only available on objects. Arrays and /// functions are also objects. String- and integer-based keys can be used /// interchangably with the framework converting between them as necessary. /// Returns true if this is a user created object. /// </summary> public bool IsUserCreated { get { return cef_v8value_t.is_user_created(_self) != 0; } } /// <summary> /// Returns true if the last method call resulted in an exception. This /// attribute exists only in the scope of the current CEF value object. /// </summary> public bool HasException { get { return cef_v8value_t.has_exception(_self) != 0; } } /// <summary> /// Returns the exception resulting from the last method call. This attribute /// exists only in the scope of the current CEF value object. /// </summary> public CefV8Exception GetException() { return CefV8Exception.FromNativeOrNull( cef_v8value_t.get_exception(_self) ); } /// <summary> /// Clears the last exception and returns true on success. /// </summary> public bool ClearException() { return cef_v8value_t.clear_exception(_self) != 0; } /// <summary> /// Returns true if this object will re-throw future exceptions. This attribute /// exists only in the scope of the current CEF value object. /// </summary> public bool WillRethrowExceptions() { return cef_v8value_t.will_rethrow_exceptions(_self) != 0; } /// <summary> /// Set whether this object will re-throw future exceptions. By default /// exceptions are not re-thrown. If a exception is re-thrown the current /// context should not be accessed again until after the exception has been /// caught and not re-thrown. Returns true on success. This attribute exists /// only in the scope of the current CEF value object. /// </summary> public bool SetRethrowExceptions(bool rethrow) { return cef_v8value_t.set_rethrow_exceptions(_self, rethrow ? 1 : 0) != 0; } /// <summary> /// Returns true if the object has a value with the specified identifier. /// </summary> public bool HasValue(string key) { fixed (char* key_str = key) { var n_key = new cef_string_t(key_str, key != null ? key.Length : 0); return cef_v8value_t.has_value_bykey(_self, &n_key) != 0; } } /// <summary> /// Returns true if the object has a value with the specified identifier. /// </summary> public bool HasValue(int index) { return cef_v8value_t.has_value_byindex(_self, index) != 0; } /// <summary> /// Deletes the value with the specified identifier and returns true on /// success. Returns false if this method is called incorrectly or an exception /// is thrown. For read-only and don't-delete values this method will return /// true even though deletion failed. /// </summary> public bool DeleteValue(string key) { fixed (char* key_str = key) { var n_key = new cef_string_t(key_str, key != null ? key.Length : 0); return cef_v8value_t.delete_value_bykey(_self, &n_key) != 0; } } /// <summary> /// Deletes the value with the specified identifier and returns true on /// success. Returns false if this method is called incorrectly, deletion fails /// or an exception is thrown. For read-only and don't-delete values this /// method will return true even though deletion failed. /// </summary> public bool DeleteValue(int index) { return cef_v8value_t.delete_value_byindex(_self, index) != 0; } /// <summary> /// Returns the value with the specified identifier on success. Returns NULL /// if this method is called incorrectly or an exception is thrown. /// </summary> public CefV8Value GetValue(string key) { fixed (char* key_str = key) { var n_key = new cef_string_t(key_str, key != null ? key.Length : 0); return CefV8Value.FromNativeOrNull( cef_v8value_t.get_value_bykey(_self, &n_key) ); } } /// <summary> /// Returns the value with the specified identifier on success. Returns NULL /// if this method is called incorrectly or an exception is thrown. /// </summary> public CefV8Value GetValue(int index) { return CefV8Value.FromNativeOrNull( cef_v8value_t.get_value_byindex(_self, index) ); } /// <summary> /// Associates a value with the specified identifier and returns true on /// success. Returns false if this method is called incorrectly or an exception /// is thrown. For read-only values this method will return true even though /// assignment failed. /// </summary> public bool SetValue(string key, CefV8Value value, CefV8PropertyAttribute attribute) { fixed (char* key_str = key) { var n_key = new cef_string_t(key_str, key != null ? key.Length : 0); return cef_v8value_t.set_value_bykey(_self, &n_key, value.ToNative(), attribute) != 0; } } /// <summary> /// Associates a value with the specified identifier and returns true on /// success. Returns false if this method is called incorrectly or an exception /// is thrown. For read-only values this method will return true even though /// assignment failed. /// </summary> public bool SetValue(int index, CefV8Value value) { return cef_v8value_t.set_value_byindex(_self, index, value.ToNative()) != 0; } /// <summary> /// Registers an identifier and returns true on success. Access to the /// identifier will be forwarded to the CefV8Accessor instance passed to /// CefV8Value::CreateObject(). Returns false if this method is called /// incorrectly or an exception is thrown. For read-only values this method /// will return true even though assignment failed. /// </summary> public bool SetValue(string key, CefV8AccessControl settings, CefV8PropertyAttribute attribute) { fixed (char* key_str = key) { var n_key = new cef_string_t(key_str, key != null ? key.Length : 0); return cef_v8value_t.set_value_byaccessor(_self, &n_key, settings, attribute) != 0; } } /// <summary> /// Read the keys for the object's values into the specified vector. Integer- /// based keys will also be returned as strings. /// </summary> public bool TryGetKeys(out string[] keys) { var list = libcef.string_list_alloc(); var result = cef_v8value_t.get_keys(_self, list) != 0; if (result) keys = cef_string_list.ToArray(list); else keys = null; libcef.string_list_free(list); return result; } /// <summary> /// Read the keys for the object's values into the specified vector. Integer- /// based keys will also be returned as strings. /// </summary> public string[] GetKeys() { string[] keys; if (TryGetKeys(out keys)) return keys; else throw new InvalidOperationException(); } /// <summary> /// Sets the user data for this object and returns true on success. Returns /// false if this method is called incorrectly. This method can only be called /// on user created objects. /// </summary> public bool SetUserData(CefUserData userData) { return cef_v8value_t.set_user_data(_self, userData != null ? (cef_base_t*)userData.ToNative() : null) != 0; } /// <summary> /// Returns the user data, if any, assigned to this object. /// </summary> public CefUserData GetUserData() { return CefUserData.FromNativeOrNull( (cef_user_data_t*)cef_v8value_t.get_user_data(_self) ); } /// <summary> /// Returns the amount of externally allocated memory registered for the /// object. /// </summary> public int GetExternallyAllocatedMemory() { return cef_v8value_t.get_externally_allocated_memory(_self); } /// <summary> /// Adjusts the amount of registered external memory for the object. Used to /// give V8 an indication of the amount of externally allocated memory that is /// kept alive by JavaScript objects. V8 uses this information to decide when /// to perform global garbage collection. Each CefV8Value tracks the amount of /// external memory associated with it and automatically decreases the global /// total by the appropriate amount on its destruction. |change_in_bytes| /// specifies the number of bytes to adjust by. This method returns the number /// of bytes associated with the object after the adjustment. This method can /// only be called on user created objects. /// </summary> public int AdjustExternallyAllocatedMemory(int changeInBytes) { return cef_v8value_t.adjust_externally_allocated_memory(_self, changeInBytes); } /// <summary> /// ARRAY METHODS - These methods are only available on arrays. /// Returns the number of elements in the array. /// </summary> public int GetArrayLength() { return cef_v8value_t.get_array_length(_self); } /// <summary> /// FUNCTION METHODS - These methods are only available on functions. /// Returns the function name. /// </summary> public string GetFunctionName() { var n_result = cef_v8value_t.get_function_name(_self); return cef_string_userfree.ToString(n_result); } /// <summary> /// Returns the function handler or NULL if not a CEF-created function. /// </summary> public CefV8Handler GetFunctionHandler() { return CefV8Handler.FromNativeOrNull( cef_v8value_t.get_function_handler(_self) ); } /// <summary> /// Execute the function using the current V8 context. This method should only /// be called from within the scope of a CefV8Handler or CefV8Accessor /// callback, or in combination with calling Enter() and Exit() on a stored /// CefV8Context reference. |object| is the receiver ('this' object) of the /// function. If |object| is empty the current context's global object will be /// used. |arguments| is the list of arguments that will be passed to the /// function. Returns the function return value on success. Returns NULL if /// this method is called incorrectly or an exception is thrown. /// </summary> public CefV8Value ExecuteFunction(CefV8Value obj, CefV8Value[] arguments) { var n_arguments = CreateArguments(arguments); cef_v8value_t* n_retval; fixed (cef_v8value_t** n_arguments_ptr = n_arguments) { n_retval = cef_v8value_t.execute_function( _self, obj != null ? obj.ToNative() : null, n_arguments != null ? (UIntPtr)n_arguments.Length : UIntPtr.Zero, n_arguments_ptr ); } return CefV8Value.FromNativeOrNull(n_retval); } /// <summary> /// Execute the function using the specified V8 context. |object| is the /// receiver ('this' object) of the function. If |object| is empty the /// specified context's global object will be used. |arguments| is the list of /// arguments that will be passed to the function. Returns the function return /// value on success. Returns NULL if this method is called incorrectly or an /// exception is thrown. /// </summary> public CefV8Value ExecuteFunctionWithContext(CefV8Context context, CefV8Value obj, CefV8Value[] arguments) { var n_arguments = CreateArguments(arguments); cef_v8value_t* n_retval; fixed (cef_v8value_t** n_arguments_ptr = n_arguments) { n_retval = cef_v8value_t.execute_function_with_context( _self, context.ToNative(), obj != null ? obj.ToNative() : null, n_arguments != null ? (UIntPtr)n_arguments.Length : UIntPtr.Zero, n_arguments_ptr ); } return CefV8Value.FromNativeOrNull(n_retval); } private static cef_v8value_t*[] CreateArguments(CefV8Value[] arguments) { if (arguments == null) return null; var length = arguments.Length; if (length == 0) return null; var result = new cef_v8value_t*[arguments.Length]; for (var i = 0; i < length; i++) { result[i] = arguments[i].ToNative(); } return result; } } }
using J2N.Threading; using J2N.Threading.Atomic; using Lucene.Net.Diagnostics; using Lucene.Net.Index.Extensions; using Lucene.Net.Store; using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Directory = Lucene.Net.Store.Directory; using Document = Lucene.Net.Documents.Document; using LineFileDocs = Lucene.Net.Util.LineFileDocs; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using TestUtil = Lucene.Net.Util.TestUtil; using ThreadState = Lucene.Net.Index.DocumentsWriterPerThreadPool.ThreadState; [TestFixture] public class TestFlushByRamOrCountsPolicy : LuceneTestCase { private static LineFileDocs lineDocFile; [OneTimeSetUp] public override void BeforeClass() { UseTempLineDocsFile = true; // LUCENENET specific - Specify to unzip the line file docs base.BeforeClass(); lineDocFile = new LineFileDocs(Random, DefaultCodecSupportsDocValues); } [OneTimeTearDown] public override void AfterClass() { lineDocFile.Dispose(); lineDocFile = null; base.AfterClass(); } [Test] public virtual void TestFlushByRam() { // LUCENENET specific - disable the test if asserts are not enabled AssumeTrue("This test requires asserts to be enabled.", Debugging.AssertsEnabled); double ramBuffer = (TestNightly ? 1 : 10) + AtLeast(2) + Random.NextDouble(); RunFlushByRam(1 + Random.Next(TestNightly ? 5 : 1), ramBuffer, false); } [Test] public virtual void TestFlushByRamLargeBuffer() { // LUCENENET specific - disable the test if asserts are not enabled AssumeTrue("This test requires asserts to be enabled.", Debugging.AssertsEnabled); // with a 256 mb ram buffer we should never stall RunFlushByRam(1 + Random.Next(TestNightly ? 5 : 1), 256d, true); } protected internal virtual void RunFlushByRam(int numThreads, double maxRamMB, bool ensureNotStalled) { int numDocumentsToIndex = 10 + AtLeast(30); AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex); Directory dir = NewDirectory(); MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy(); MockAnalyzer analyzer = new MockAnalyzer(Random); analyzer.MaxTokenLength = TestUtil.NextInt32(Random, 1, IndexWriter.MAX_TERM_LENGTH); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetFlushPolicy(flushPolicy); int numDWPT = 1 + AtLeast(2); DocumentsWriterPerThreadPool threadPool = new DocumentsWriterPerThreadPool(numDWPT); iwc.SetIndexerThreadPool(threadPool); iwc.SetRAMBufferSizeMB(maxRamMB); iwc.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH); iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH); IndexWriter writer = new IndexWriter(dir, iwc); flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy; Assert.IsFalse(flushPolicy.FlushOnDocCount); Assert.IsFalse(flushPolicy.FlushOnDeleteTerms); Assert.IsTrue(flushPolicy.FlushOnRAM); DocumentsWriter docsWriter = writer.DocsWriter; Assert.IsNotNull(docsWriter); DocumentsWriterFlushControl flushControl = docsWriter.flushControl; Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init"); IndexThread[] threads = new IndexThread[numThreads]; for (int x = 0; x < threads.Length; x++) { threads[x] = new IndexThread(numDocs, writer, lineDocFile, false); threads[x].Start(); } for (int x = 0; x < threads.Length; x++) { threads[x].Join(); } long maxRAMBytes = (long)(iwc.RAMBufferSizeMB * 1024.0 * 1024.0); Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due numThreads=" + numThreads); Assert.AreEqual(numDocumentsToIndex, writer.NumDocs); Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc); Assert.IsTrue(flushPolicy.peakBytesWithoutFlush <= maxRAMBytes, "peak bytes without flush exceeded watermark"); AssertActiveBytesAfter(flushControl); if (flushPolicy.hasMarkedPending) { Assert.IsTrue(maxRAMBytes < flushControl.peakActiveBytes); } if (ensureNotStalled) { Assert.IsFalse(docsWriter.flushControl.stallControl.WasStalled); } writer.Dispose(); Assert.AreEqual(0, flushControl.ActiveBytes); dir.Dispose(); } [Test] public virtual void TestFlushDocCount() { // LUCENENET specific - disable the test if asserts are not enabled AssumeTrue("This test requires asserts to be enabled.", Debugging.AssertsEnabled); int[] numThreads = new int[] { 2 + AtLeast(1), 1 }; for (int i = 0; i < numThreads.Length; i++) { int numDocumentsToIndex = 50 + AtLeast(30); AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex); Directory dir = NewDirectory(); MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetFlushPolicy(flushPolicy); int numDWPT = 1 + AtLeast(2); DocumentsWriterPerThreadPool threadPool = new DocumentsWriterPerThreadPool(numDWPT); iwc.SetIndexerThreadPool(threadPool); iwc.SetMaxBufferedDocs(2 + AtLeast(10)); iwc.SetRAMBufferSizeMB(IndexWriterConfig.DISABLE_AUTO_FLUSH); iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH); IndexWriter writer = new IndexWriter(dir, iwc); flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy; Assert.IsTrue(flushPolicy.FlushOnDocCount); Assert.IsFalse(flushPolicy.FlushOnDeleteTerms); Assert.IsFalse(flushPolicy.FlushOnRAM); DocumentsWriter docsWriter = writer.DocsWriter; Assert.IsNotNull(docsWriter); DocumentsWriterFlushControl flushControl = docsWriter.flushControl; Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init"); IndexThread[] threads = new IndexThread[numThreads[i]]; for (int x = 0; x < threads.Length; x++) { threads[x] = new IndexThread(numDocs, writer, lineDocFile, false); threads[x].Start(); } for (int x = 0; x < threads.Length; x++) { threads[x].Join(); } Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due numThreads=" + numThreads[i]); Assert.AreEqual(numDocumentsToIndex, writer.NumDocs); Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc); Assert.IsTrue(flushPolicy.peakDocCountWithoutFlush <= iwc.MaxBufferedDocs, "peak bytes without flush exceeded watermark"); AssertActiveBytesAfter(flushControl); writer.Dispose(); Assert.AreEqual(0, flushControl.ActiveBytes); dir.Dispose(); } } [Test] public virtual void TestRandom() { // LUCENENET specific - disable the test if asserts are not enabled AssumeTrue("This test requires asserts to be enabled.", Debugging.AssertsEnabled); int numThreads = 1 + Random.Next(8); int numDocumentsToIndex = 50 + AtLeast(70); AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex); Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); MockDefaultFlushPolicy flushPolicy = new MockDefaultFlushPolicy(); iwc.SetFlushPolicy(flushPolicy); int numDWPT = 1 + Random.Next(8); DocumentsWriterPerThreadPool threadPool = new DocumentsWriterPerThreadPool(numDWPT); iwc.SetIndexerThreadPool(threadPool); IndexWriter writer = new IndexWriter(dir, iwc); flushPolicy = (MockDefaultFlushPolicy)writer.Config.FlushPolicy; DocumentsWriter docsWriter = writer.DocsWriter; Assert.IsNotNull(docsWriter); DocumentsWriterFlushControl flushControl = docsWriter.flushControl; Assert.AreEqual(0, flushControl.FlushBytes, " bytes must be 0 after init"); IndexThread[] threads = new IndexThread[numThreads]; for (int x = 0; x < threads.Length; x++) { threads[x] = new IndexThread(numDocs, writer, lineDocFile, true); threads[x].Start(); } for (int x = 0; x < threads.Length; x++) { threads[x].Join(); } Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due"); Assert.AreEqual(numDocumentsToIndex, writer.NumDocs); Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc); if (flushPolicy.FlushOnRAM && !flushPolicy.FlushOnDocCount && !flushPolicy.FlushOnDeleteTerms) { long maxRAMBytes = (long)(iwc.RAMBufferSizeMB * 1024.0 * 1024.0); Assert.IsTrue(flushPolicy.peakBytesWithoutFlush <= maxRAMBytes, "peak bytes without flush exceeded watermark"); if (flushPolicy.hasMarkedPending) { assertTrue("max: " + maxRAMBytes + " " + flushControl.peakActiveBytes, maxRAMBytes <= flushControl.peakActiveBytes); } } AssertActiveBytesAfter(flushControl); writer.Commit(); Assert.AreEqual(0, flushControl.ActiveBytes); IndexReader r = DirectoryReader.Open(dir); Assert.AreEqual(numDocumentsToIndex, r.NumDocs); Assert.AreEqual(numDocumentsToIndex, r.MaxDoc); if (!flushPolicy.FlushOnRAM) { assertFalse("never stall if we don't flush on RAM", docsWriter.flushControl.stallControl.WasStalled); assertFalse("never block if we don't flush on RAM", docsWriter.flushControl.stallControl.HasBlocked); } r.Dispose(); writer.Dispose(); dir.Dispose(); } [Test] [Slow] // LUCENENET: occasionally public virtual void TestStallControl() { // LUCENENET specific - disable the test if asserts are not enabled AssumeTrue("This test requires asserts to be enabled.", Debugging.AssertsEnabled); int[] numThreads = new int[] { 4 + Random.Next(8), 1 }; int numDocumentsToIndex = 50 + Random.Next(50); for (int i = 0; i < numThreads.Length; i++) { AtomicInt32 numDocs = new AtomicInt32(numDocumentsToIndex); MockDirectoryWrapper dir = NewMockDirectory(); // mock a very slow harddisk sometimes here so that flushing is very slow dir.Throttling = Throttling.SOMETIMES; IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); iwc.SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH); iwc.SetMaxBufferedDeleteTerms(IndexWriterConfig.DISABLE_AUTO_FLUSH); FlushPolicy flushPolicy = new FlushByRamOrCountsPolicy(); iwc.SetFlushPolicy(flushPolicy); DocumentsWriterPerThreadPool threadPool = new DocumentsWriterPerThreadPool(numThreads[i] == 1 ? 1 : 2); iwc.SetIndexerThreadPool(threadPool); // with such a small ram buffer we should be stalled quiet quickly iwc.SetRAMBufferSizeMB(0.25); IndexWriter writer = new IndexWriter(dir, iwc); IndexThread[] threads = new IndexThread[numThreads[i]]; for (int x = 0; x < threads.Length; x++) { threads[x] = new IndexThread(numDocs, writer, lineDocFile, false); threads[x].Start(); } for (int x = 0; x < threads.Length; x++) { threads[x].Join(); } DocumentsWriter docsWriter = writer.DocsWriter; Assert.IsNotNull(docsWriter); DocumentsWriterFlushControl flushControl = docsWriter.flushControl; Assert.AreEqual(0, flushControl.FlushBytes, " all flushes must be due"); Assert.AreEqual(numDocumentsToIndex, writer.NumDocs); Assert.AreEqual(numDocumentsToIndex, writer.MaxDoc); if (numThreads[i] == 1) { assertFalse("single thread must not block numThreads: " + numThreads[i], docsWriter.flushControl.stallControl.HasBlocked); } if (docsWriter.flushControl.peakNetBytes > (2d * iwc.RAMBufferSizeMB * 1024d * 1024d)) { Assert.IsTrue(docsWriter.flushControl.stallControl.WasStalled); } AssertActiveBytesAfter(flushControl); writer.Dispose(true); dir.Dispose(); } } internal virtual void AssertActiveBytesAfter(DocumentsWriterFlushControl flushControl) { IEnumerator<ThreadState> allActiveThreads = flushControl.AllActiveThreadStates(); long bytesUsed = 0; while (allActiveThreads.MoveNext()) { ThreadState next = allActiveThreads.Current; if (next.dwpt != null) { bytesUsed += next.dwpt.BytesUsed; } } Assert.AreEqual(bytesUsed, flushControl.ActiveBytes); } public class IndexThread : ThreadJob { internal IndexWriter writer; internal LiveIndexWriterConfig iwc; internal LineFileDocs docs; internal AtomicInt32 pendingDocs; internal readonly bool doRandomCommit; public IndexThread(AtomicInt32 pendingDocs, IndexWriter writer, LineFileDocs docs, bool doRandomCommit) { this.pendingDocs = pendingDocs; this.writer = writer; iwc = writer.Config; this.docs = docs; this.doRandomCommit = doRandomCommit; } public override void Run() { try { long ramSize = 0; while (pendingDocs.DecrementAndGet() > -1) { Document doc = docs.NextDoc(); writer.AddDocument(doc); long newRamSize = writer.RamSizeInBytes(); if (newRamSize != ramSize) { ramSize = newRamSize; } if (doRandomCommit) { if (Rarely()) { writer.Commit(); } } } writer.Commit(); } catch (Exception ex) { Console.WriteLine("FAILED exc:"); Console.WriteLine(ex.StackTrace); throw new Exception(ex.Message, ex); } } } private class MockDefaultFlushPolicy : FlushByRamOrCountsPolicy { internal long peakBytesWithoutFlush = int.MinValue; internal long peakDocCountWithoutFlush = int.MinValue; internal bool hasMarkedPending = false; public override void OnDelete(DocumentsWriterFlushControl control, ThreadState state) { List<ThreadState> pending = new List<ThreadState>(); List<ThreadState> notPending = new List<ThreadState>(); FindPending(control, pending, notPending); bool flushCurrent = state.IsFlushPending; ThreadState toFlush; if (state.IsFlushPending) { toFlush = state; } else if (FlushOnDeleteTerms && state.DocumentsWriterPerThread.NumDeleteTerms >= m_indexWriterConfig.MaxBufferedDeleteTerms) { toFlush = state; } else { toFlush = null; } base.OnDelete(control, state); if (toFlush != null) { if (flushCurrent) { Assert.IsTrue(pending.Remove(toFlush)); } else { Assert.IsTrue(notPending.Remove(toFlush)); } Assert.IsTrue(toFlush.IsFlushPending); hasMarkedPending = true; } foreach (ThreadState threadState in notPending) { Assert.IsFalse(threadState.IsFlushPending); } } public override void OnInsert(DocumentsWriterFlushControl control, ThreadState state) { List<ThreadState> pending = new List<ThreadState>(); List<ThreadState> notPending = new List<ThreadState>(); FindPending(control, pending, notPending); bool flushCurrent = state.IsFlushPending; long activeBytes = control.ActiveBytes; ThreadState toFlush; if (state.IsFlushPending) { toFlush = state; } else if (FlushOnDocCount && state.DocumentsWriterPerThread.NumDocsInRAM >= m_indexWriterConfig.MaxBufferedDocs) { toFlush = state; } else if (FlushOnRAM && activeBytes >= (long)(m_indexWriterConfig.RAMBufferSizeMB * 1024.0 * 1024.0)) { toFlush = FindLargestNonPendingWriter(control, state); Assert.IsFalse(toFlush.IsFlushPending); } else { toFlush = null; } base.OnInsert(control, state); if (toFlush != null) { if (flushCurrent) { Assert.IsTrue(pending.Remove(toFlush)); } else { Assert.IsTrue(notPending.Remove(toFlush)); } Assert.IsTrue(toFlush.IsFlushPending); hasMarkedPending = true; } else { peakBytesWithoutFlush = Math.Max(activeBytes, peakBytesWithoutFlush); peakDocCountWithoutFlush = Math.Max(state.DocumentsWriterPerThread.NumDocsInRAM, peakDocCountWithoutFlush); } foreach (ThreadState threadState in notPending) { Assert.IsFalse(threadState.IsFlushPending); } } } internal static void FindPending(DocumentsWriterFlushControl flushControl, List<ThreadState> pending, List<ThreadState> notPending) { IEnumerator<ThreadState> allActiveThreads = flushControl.AllActiveThreadStates(); while (allActiveThreads.MoveNext()) { ThreadState next = allActiveThreads.Current; if (next.IsFlushPending) { pending.Add(next); } else { notPending.Add(next); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; namespace GameRocket { internal class JSON { public const int TOKEN_NONE = 0; public const int TOKEN_CURLY_OPEN = 1; public const int TOKEN_CURLY_CLOSE = 2; public const int TOKEN_SQUARED_OPEN = 3; public const int TOKEN_SQUARED_CLOSE = 4; public const int TOKEN_COLON = 5; public const int TOKEN_COMMA = 6; public const int TOKEN_STRING = 7; public const int TOKEN_NUMBER = 8; public const int TOKEN_TRUE = 9; public const int TOKEN_FALSE = 10; public const int TOKEN_NULL = 11; private const int BUILDER_CAPACITY = 5000; private static JSON instance = new JSON(); /// <summary> /// On decoding, this value holds the position at which the parse failed (-1 = no error). /// </summary> protected int lastErrorIndex = -1; protected string lastDecode = ""; /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List<object>, a Dictionary<string,object>, a double, a string, null, true, or false</returns> public static object JsonDecode(string json) { // save the string for debug information JSON.instance.lastDecode = json; if (json != null) { char[] charArray = json.ToCharArray(); int index = 0; bool success = true; object value = JSON.instance.ParseValue(charArray, ref index, ref success); if (success) { JSON.instance.lastErrorIndex = -1; } else { JSON.instance.lastErrorIndex = index; } return value; } else { return null; } } /// <summary> /// Converts a Dictionary<string,object> / List<object> object into a JSON string /// </summary> /// <param name="json">A Dictionary<string,object> / List<object></param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string JsonEncode(object json) { StringBuilder builder = new StringBuilder(BUILDER_CAPACITY); bool success = JSON.instance.SerializeValue(json, builder); return (success ? builder.ToString() : null); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static bool LastDecodeSuccessful() { return (JSON.instance.lastErrorIndex == -1); } /// <summary> /// On decoding, this function returns the position at which the parse failed (-1 = no error). /// </summary> /// <returns></returns> public static int GetLastErrorIndex() { return JSON.instance.lastErrorIndex; } /// <summary> /// If a decoding error occurred, this function returns a piece of the JSON string /// at which the error took place. To ease debugging. /// </summary> /// <returns></returns> public static string GetLastErrorSnippet() { if (JSON.instance.lastErrorIndex == -1) { return ""; } else { int startIndex = JSON.instance.lastErrorIndex - 5; int endIndex = JSON.instance.lastErrorIndex + 15; if (startIndex < 0) { startIndex = 0; } if (endIndex >= JSON.instance.lastDecode.Length) { endIndex = JSON.instance.lastDecode.Length - 1; } return JSON.instance.lastDecode.Substring(startIndex, endIndex - startIndex + 1); } } protected Dictionary<string,object> ParseObject(char[] json, ref int index) { Dictionary<string,object> table = new Dictionary<string,object>(); int token; // { NextToken(json, ref index); bool done = false; while (!done) { token = LookAhead(json, index); if (token == JSON.TOKEN_NONE) { return null; } else if (token == JSON.TOKEN_COMMA) { NextToken(json, ref index); } else if (token == JSON.TOKEN_CURLY_CLOSE) { NextToken(json, ref index); return table; } else { // name string name = ParseString(json, ref index); if (name == null) { return null; } // : token = NextToken(json, ref index); if (token != JSON.TOKEN_COLON) { return null; } // value bool success = true; object value = ParseValue(json, ref index, ref success); if (!success) { return null; } table[name] = value; } } return table; } protected List<object> ParseArray(char[] json, ref int index) { List<object> array = new List<object>(); // [ NextToken(json, ref index); bool done = false; while (!done) { int token = LookAhead(json, index); if (token == JSON.TOKEN_NONE) { return null; } else if (token == JSON.TOKEN_COMMA) { NextToken(json, ref index); } else if (token == JSON.TOKEN_SQUARED_CLOSE) { NextToken(json, ref index); break; } else { bool success = true; object value = ParseValue(json, ref index, ref success); if (!success) { return null; } array.Add(value); } } return array; } protected object ParseValue(char[] json, ref int index, ref bool success) { switch (LookAhead(json, index)) { case JSON.TOKEN_STRING: return ParseString(json, ref index); case JSON.TOKEN_NUMBER: return ParseNumber(json, ref index); case JSON.TOKEN_CURLY_OPEN: return ParseObject(json, ref index); case JSON.TOKEN_SQUARED_OPEN: return ParseArray(json, ref index); case JSON.TOKEN_TRUE: NextToken(json, ref index); return Boolean.Parse("TRUE"); case JSON.TOKEN_FALSE: NextToken(json, ref index); return Boolean.Parse("FALSE"); case JSON.TOKEN_NULL: NextToken(json, ref index); return null; case JSON.TOKEN_NONE: break; } success = false; return null; } protected string ParseString(char[] json, ref int index) { string s = ""; char c; EatWhitespace(json, ref index); // " c = json[index++]; bool complete = false; while (!complete) { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { complete = true; break; } else if (c == '\\') { if (index == json.Length) { break; } c = json[index++]; if (c == '"') { s += '"'; } else if (c == '\\') { s += '\\'; } else if (c == '/') { s += '/'; } else if (c == 'b') { s += '\b'; } else if (c == 'f') { s += '\f'; } else if (c == 'n') { s += '\n'; } else if (c == 'r') { s += '\r'; } else if (c == 't') { s += '\t'; } else if (c == 'u') { int remainingLength = json.Length - index; if (remainingLength >= 4) { // fetch the next 4 chars char[] unicodeCharArray = new char[4]; Array.Copy(json, index, unicodeCharArray, 0, 4); // parse the 32 bit hex into an integer codepoint uint codePoint = UInt32.Parse(new string(unicodeCharArray), NumberStyles.HexNumber); // convert the integer codepoint to a unicode char and add to string s += Char.ConvertFromUtf32((int)codePoint); // skip 4 chars index += 4; } else { break; } } } else { s += c; } } if (!complete) { return null; } return s; } protected double ParseNumber(char[] json, ref int index) { EatWhitespace(json, ref index); int lastIndex = GetLastIndexOfNumber(json, index); int charLength = (lastIndex - index) + 1; char[] numberCharArray = new char[charLength]; Array.Copy(json, index, numberCharArray, 0, charLength); index = lastIndex + 1; return Double.Parse(new string(numberCharArray), CultureInfo.InvariantCulture); } protected int GetLastIndexOfNumber(char[] json, int index) { int lastIndex; for (lastIndex = index; lastIndex < json.Length; lastIndex++) { if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) { break; } } return lastIndex - 1; } protected void EatWhitespace(char[] json, ref int index) { for (; index < json.Length; index++) { if (" \t\n\r".IndexOf(json[index]) == -1) { break; } } } protected int LookAhead(char[] json, int index) { int saveIndex = index; return NextToken(json, ref saveIndex); } protected int NextToken(char[] json, ref int index) { EatWhitespace(json, ref index); if (index == json.Length) { return JSON.TOKEN_NONE; } char c = json[index]; index++; switch (c) { case '{': return JSON.TOKEN_CURLY_OPEN; case '}': return JSON.TOKEN_CURLY_CLOSE; case '[': return JSON.TOKEN_SQUARED_OPEN; case ']': return JSON.TOKEN_SQUARED_CLOSE; case ',': return JSON.TOKEN_COMMA; case '"': return JSON.TOKEN_STRING; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return JSON.TOKEN_NUMBER; case ':': return JSON.TOKEN_COLON; } index--; int remainingLength = json.Length - index; // false if (remainingLength >= 5) { if (json[index] == 'f' && json[index + 1] == 'a' && json[index + 2] == 'l' && json[index + 3] == 's' && json[index + 4] == 'e') { index += 5; return JSON.TOKEN_FALSE; } } // true if (remainingLength >= 4) { if (json[index] == 't' && json[index + 1] == 'r' && json[index + 2] == 'u' && json[index + 3] == 'e') { index += 4; return JSON.TOKEN_TRUE; } } // null if (remainingLength >= 4) { if (json[index] == 'n' && json[index + 1] == 'u' && json[index + 2] == 'l' && json[index + 3] == 'l') { index += 4; return JSON.TOKEN_NULL; } } return JSON.TOKEN_NONE; } protected bool SerializeObjectOrArray(object objectOrArray, StringBuilder builder) { if (objectOrArray is Dictionary<string,object>) { return SerializeObject((Dictionary<string,object>)objectOrArray, builder); } else if (objectOrArray is List<object>) { return SerializeArray((List<object>)objectOrArray, builder); } else { return false; } } protected bool SerializeObject(Dictionary<string,object> anObject, StringBuilder builder) { builder.Append("{"); IDictionaryEnumerator e = anObject.GetEnumerator(); bool first = true; while (e.MoveNext()) { string key = e.Key.ToString(); object value = e.Value; if (!first) { builder.Append(", "); } SerializeString(key, builder); builder.Append(":"); if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("}"); return true; } protected bool SerializeArray(IList anArray, StringBuilder builder) { builder.Append("["); bool first = true; for (int i = 0; i < anArray.Count; i++) { object value = anArray[i]; if (!first) { builder.Append(", "); } if (!SerializeValue(value, builder)) { return false; } first = false; } builder.Append("]"); return true; } protected bool SerializeValue(object value, StringBuilder builder) { if (value is string) { SerializeString((string)value, builder); } else if (value is Dictionary<string,object>) { SerializeObject((Dictionary<string,object>)value, builder); } else if (value is IList) { SerializeArray((IList)value, builder); } else if (IsNumeric(value)) { SerializeNumber(Convert.ToDouble(value), builder); } else if ((value is Boolean) && ((Boolean)value == true)) { builder.Append("true"); } else if ((value is Boolean) && ((Boolean)value == false)) { builder.Append("false"); } else if (value == null) { builder.Append("null"); } else { return false; } return true; } protected void SerializeString(string aString, StringBuilder builder) { builder.Append("\""); char[] charArray = aString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { char c = charArray[i]; if (c == '"') { builder.Append("\\\""); } else if (c == '\\') { builder.Append("\\\\"); } else if (c == '\b') { builder.Append("\\b"); } else if (c == '\f') { builder.Append("\\f"); } else if (c == '\n') { builder.Append("\\n"); } else if (c == '\r') { builder.Append("\\r"); } else if (c == '\t') { builder.Append("\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append("\""); } protected void SerializeNumber(double number, StringBuilder builder) { builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture)); } /// <summary> /// Determines if a given object is numeric in any way /// (can be integer, double, etc). C# has no pretty way to do this. /// </summary> protected bool IsNumeric(object o) { try { Double.Parse(o.ToString()); } catch (Exception) { return false; } return true; } } }
#if REAL_T_IS_DOUBLE using real_t = System.Double; #else using real_t = System.Single; #endif using System; using System.Runtime.InteropServices; namespace Godot { /// <summary> /// 3-element structure that can be used to represent 3D grid coordinates or sets of integers. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3i : IEquatable<Vector3i> { /// <summary> /// Enumerated index values for the axes. /// Returned by <see cref="MaxAxis"/> and <see cref="MinAxis"/>. /// </summary> public enum Axis { /// <summary> /// The vector's X axis. /// </summary> X = 0, /// <summary> /// The vector's Y axis. /// </summary> Y, /// <summary> /// The vector's Z axis. /// </summary> Z } /// <summary> /// The vector's X component. Also accessible by using the index position <c>[0]</c>. /// </summary> public int x; /// <summary> /// The vector's Y component. Also accessible by using the index position <c>[1]</c>. /// </summary> public int y; /// <summary> /// The vector's Z component. Also accessible by using the index position <c>[2]</c>. /// </summary> public int z; /// <summary> /// Access vector components using their <paramref name="index"/>. /// </summary> /// <exception cref="IndexOutOfRangeException"> /// Thrown when the given the <paramref name="index"/> is not 0, 1 or 2. /// </exception> /// <value> /// <c>[0]</c> is equivalent to <see cref="x"/>, /// <c>[1]</c> is equivalent to <see cref="y"/>, /// <c>[2]</c> is equivalent to <see cref="z"/>. /// </value> public int this[int index] { get { switch (index) { case 0: return x; case 1: return y; case 2: return z; default: throw new IndexOutOfRangeException(); } } set { switch (index) { case 0: x = value; return; case 1: y = value; return; case 2: z = value; return; default: throw new IndexOutOfRangeException(); } } } /// <summary> /// Returns a new vector with all components in absolute values (i.e. positive). /// </summary> /// <returns>A vector with <see cref="Mathf.Abs(int)"/> called on each component.</returns> public Vector3i Abs() { return new Vector3i(Mathf.Abs(x), Mathf.Abs(y), Mathf.Abs(z)); } /// <summary> /// Returns a new vector with all components clamped between the /// components of <paramref name="min"/> and <paramref name="max"/> using /// <see cref="Mathf.Clamp(int, int, int)"/>. /// </summary> /// <param name="min">The vector with minimum allowed values.</param> /// <param name="max">The vector with maximum allowed values.</param> /// <returns>The vector with all components clamped.</returns> public Vector3i Clamp(Vector3i min, Vector3i max) { return new Vector3i ( Mathf.Clamp(x, min.x, max.x), Mathf.Clamp(y, min.y, max.y), Mathf.Clamp(z, min.z, max.z) ); } /// <summary> /// Returns the squared distance between this vector and <paramref name="b"/>. /// This method runs faster than <see cref="DistanceTo"/>, so prefer it if /// you need to compare vectors or need the squared distance for some formula. /// </summary> /// <param name="b">The other vector to use.</param> /// <returns>The squared distance between the two vectors.</returns> public int DistanceSquaredTo(Vector3i b) { return (b - this).LengthSquared(); } /// <summary> /// Returns the distance between this vector and <paramref name="b"/>. /// </summary> /// <seealso cref="DistanceSquaredTo(Vector3i)"/> /// <param name="b">The other vector to use.</param> /// <returns>The distance between the two vectors.</returns> public real_t DistanceTo(Vector3i b) { return (b - this).Length(); } /// <summary> /// Returns the dot product of this vector and <paramref name="b"/>. /// </summary> /// <param name="b">The other vector to use.</param> /// <returns>The dot product of the two vectors.</returns> public int Dot(Vector3i b) { return x * b.x + y * b.y + z * b.z; } /// <summary> /// Returns the length (magnitude) of this vector. /// </summary> /// <seealso cref="LengthSquared"/> /// <returns>The length of this vector.</returns> public real_t Length() { int x2 = x * x; int y2 = y * y; int z2 = z * z; return Mathf.Sqrt(x2 + y2 + z2); } /// <summary> /// Returns the squared length (squared magnitude) of this vector. /// This method runs faster than <see cref="Length"/>, so prefer it if /// you need to compare vectors or need the squared length for some formula. /// </summary> /// <returns>The squared length of this vector.</returns> public int LengthSquared() { int x2 = x * x; int y2 = y * y; int z2 = z * z; return x2 + y2 + z2; } /// <summary> /// Returns the axis of the vector's largest value. See <see cref="Axis"/>. /// If all components are equal, this method returns <see cref="Axis.X"/>. /// </summary> /// <returns>The index of the largest axis.</returns> public Axis MaxAxis() { return x < y ? (y < z ? Axis.Z : Axis.Y) : (x < z ? Axis.Z : Axis.X); } /// <summary> /// Returns the axis of the vector's smallest value. See <see cref="Axis"/>. /// If all components are equal, this method returns <see cref="Axis.Z"/>. /// </summary> /// <returns>The index of the smallest axis.</returns> public Axis MinAxis() { return x < y ? (x < z ? Axis.X : Axis.Z) : (y < z ? Axis.Y : Axis.Z); } /// <summary> /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components /// and <paramref name="mod"/>. /// </summary> /// <param name="mod">A value representing the divisor of the operation.</param> /// <returns> /// A vector with each component <see cref="Mathf.PosMod(int, int)"/> by <paramref name="mod"/>. /// </returns> public Vector3i PosMod(int mod) { Vector3i v = this; v.x = Mathf.PosMod(v.x, mod); v.y = Mathf.PosMod(v.y, mod); v.z = Mathf.PosMod(v.z, mod); return v; } /// <summary> /// Returns a vector composed of the <see cref="Mathf.PosMod(int, int)"/> of this vector's components /// and <paramref name="modv"/>'s components. /// </summary> /// <param name="modv">A vector representing the divisors of the operation.</param> /// <returns> /// A vector with each component <see cref="Mathf.PosMod(int, int)"/> by <paramref name="modv"/>'s components. /// </returns> public Vector3i PosMod(Vector3i modv) { Vector3i v = this; v.x = Mathf.PosMod(v.x, modv.x); v.y = Mathf.PosMod(v.y, modv.y); v.z = Mathf.PosMod(v.z, modv.z); return v; } /// <summary> /// Returns a vector with each component set to one or negative one, depending /// on the signs of this vector's components, or zero if the component is zero, /// by calling <see cref="Mathf.Sign(int)"/> on each component. /// </summary> /// <returns>A vector with all components as either <c>1</c>, <c>-1</c>, or <c>0</c>.</returns> public Vector3i Sign() { Vector3i v = this; v.x = Mathf.Sign(v.x); v.y = Mathf.Sign(v.y); v.z = Mathf.Sign(v.z); return v; } // Constants private static readonly Vector3i _zero = new Vector3i(0, 0, 0); private static readonly Vector3i _one = new Vector3i(1, 1, 1); private static readonly Vector3i _up = new Vector3i(0, 1, 0); private static readonly Vector3i _down = new Vector3i(0, -1, 0); private static readonly Vector3i _right = new Vector3i(1, 0, 0); private static readonly Vector3i _left = new Vector3i(-1, 0, 0); private static readonly Vector3i _forward = new Vector3i(0, 0, -1); private static readonly Vector3i _back = new Vector3i(0, 0, 1); /// <summary> /// Zero vector, a vector with all components set to <c>0</c>. /// </summary> /// <value>Equivalent to <c>new Vector3i(0, 0, 0)</c>.</value> public static Vector3i Zero { get { return _zero; } } /// <summary> /// One vector, a vector with all components set to <c>1</c>. /// </summary> /// <value>Equivalent to <c>new Vector3i(1, 1, 1)</c>.</value> public static Vector3i One { get { return _one; } } /// <summary> /// Up unit vector. /// </summary> /// <value>Equivalent to <c>new Vector3i(0, 1, 0)</c>.</value> public static Vector3i Up { get { return _up; } } /// <summary> /// Down unit vector. /// </summary> /// <value>Equivalent to <c>new Vector3i(0, -1, 0)</c>.</value> public static Vector3i Down { get { return _down; } } /// <summary> /// Right unit vector. Represents the local direction of right, /// and the global direction of east. /// </summary> /// <value>Equivalent to <c>new Vector3i(1, 0, 0)</c>.</value> public static Vector3i Right { get { return _right; } } /// <summary> /// Left unit vector. Represents the local direction of left, /// and the global direction of west. /// </summary> /// <value>Equivalent to <c>new Vector3i(-1, 0, 0)</c>.</value> public static Vector3i Left { get { return _left; } } /// <summary> /// Forward unit vector. Represents the local direction of forward, /// and the global direction of north. /// </summary> /// <value>Equivalent to <c>new Vector3i(0, 0, -1)</c>.</value> public static Vector3i Forward { get { return _forward; } } /// <summary> /// Back unit vector. Represents the local direction of back, /// and the global direction of south. /// </summary> /// <value>Equivalent to <c>new Vector3i(0, 0, 1)</c>.</value> public static Vector3i Back { get { return _back; } } /// <summary> /// Constructs a new <see cref="Vector3i"/> with the given components. /// </summary> /// <param name="x">The vector's X component.</param> /// <param name="y">The vector's Y component.</param> /// <param name="z">The vector's Z component.</param> public Vector3i(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } /// <summary> /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3i"/>. /// </summary> /// <param name="vi">The existing <see cref="Vector3i"/>.</param> public Vector3i(Vector3i vi) { this.x = vi.x; this.y = vi.y; this.z = vi.z; } /// <summary> /// Constructs a new <see cref="Vector3i"/> from an existing <see cref="Vector3"/> /// by rounding the components via <see cref="Mathf.RoundToInt(real_t)"/>. /// </summary> /// <param name="v">The <see cref="Vector3"/> to convert.</param> public Vector3i(Vector3 v) { this.x = Mathf.RoundToInt(v.x); this.y = Mathf.RoundToInt(v.y); this.z = Mathf.RoundToInt(v.z); } public static Vector3i operator +(Vector3i left, Vector3i right) { left.x += right.x; left.y += right.y; left.z += right.z; return left; } public static Vector3i operator -(Vector3i left, Vector3i right) { left.x -= right.x; left.y -= right.y; left.z -= right.z; return left; } public static Vector3i operator -(Vector3i vec) { vec.x = -vec.x; vec.y = -vec.y; vec.z = -vec.z; return vec; } public static Vector3i operator *(Vector3i vec, int scale) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3i operator *(int scale, Vector3i vec) { vec.x *= scale; vec.y *= scale; vec.z *= scale; return vec; } public static Vector3i operator *(Vector3i left, Vector3i right) { left.x *= right.x; left.y *= right.y; left.z *= right.z; return left; } public static Vector3i operator /(Vector3i vec, int divisor) { vec.x /= divisor; vec.y /= divisor; vec.z /= divisor; return vec; } public static Vector3i operator /(Vector3i vec, Vector3i divisorv) { vec.x /= divisorv.x; vec.y /= divisorv.y; vec.z /= divisorv.z; return vec; } public static Vector3i operator %(Vector3i vec, int divisor) { vec.x %= divisor; vec.y %= divisor; vec.z %= divisor; return vec; } public static Vector3i operator %(Vector3i vec, Vector3i divisorv) { vec.x %= divisorv.x; vec.y %= divisorv.y; vec.z %= divisorv.z; return vec; } public static Vector3i operator &(Vector3i vec, int and) { vec.x &= and; vec.y &= and; vec.z &= and; return vec; } public static Vector3i operator &(Vector3i vec, Vector3i andv) { vec.x &= andv.x; vec.y &= andv.y; vec.z &= andv.z; return vec; } public static bool operator ==(Vector3i left, Vector3i right) { return left.Equals(right); } public static bool operator !=(Vector3i left, Vector3i right) { return !left.Equals(right); } public static bool operator <(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z < right.z; else return left.y < right.y; } return left.x < right.x; } public static bool operator >(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z > right.z; else return left.y > right.y; } return left.x > right.x; } public static bool operator <=(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z <= right.z; else return left.y < right.y; } return left.x < right.x; } public static bool operator >=(Vector3i left, Vector3i right) { if (left.x == right.x) { if (left.y == right.y) return left.z >= right.z; else return left.y > right.y; } return left.x > right.x; } /// <summary> /// Converts this <see cref="Vector3i"/> to a <see cref="Vector3"/>. /// </summary> /// <param name="value">The vector to convert.</param> public static implicit operator Vector3(Vector3i value) { return new Vector3(value.x, value.y, value.z); } /// <summary> /// Converts a <see cref="Vector3"/> to a <see cref="Vector3i"/>. /// </summary> /// <param name="value">The vector to convert.</param> public static explicit operator Vector3i(Vector3 value) { return new Vector3i(value); } /// <summary> /// Returns <see langword="true"/> if this vector and <paramref name="obj"/> are equal. /// </summary> /// <param name="obj">The other object to compare.</param> /// <returns>Whether or not the vector and the other object are equal.</returns> public override bool Equals(object obj) { if (obj is Vector3i) { return Equals((Vector3i)obj); } return false; } /// <summary> /// Returns <see langword="true"/> if this vector and <paramref name="other"/> are equal /// </summary> /// <param name="other">The other vector to compare.</param> /// <returns>Whether or not the vectors are equal.</returns> public bool Equals(Vector3i other) { return x == other.x && y == other.y && z == other.z; } /// <summary> /// Serves as the hash function for <see cref="Vector3i"/>. /// </summary> /// <returns>A hash code for this vector.</returns> public override int GetHashCode() { return y.GetHashCode() ^ x.GetHashCode() ^ z.GetHashCode(); } /// <summary> /// Converts this <see cref="Vector3i"/> to a string. /// </summary> /// <returns>A string representation of this vector.</returns> public override string ToString() { return $"({x}, {y}, {z})"; } /// <summary> /// Converts this <see cref="Vector3i"/> to a string with the given <paramref name="format"/>. /// </summary> /// <returns>A string representation of this vector.</returns> public string ToString(string format) { return $"({x.ToString(format)}, {y.ToString(format)}, {z.ToString(format)})"; } } }
#region License /* * Copyright 2007 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Reflection; using System.Xml.Serialization; using System.Web.Services; using System.Web.Services.Protocols; using System.Web.Services.Description; using System.ServiceModel; using System.ServiceModel.Description; using NUnit.Framework; using Spring.Core.IO; using Spring.Context; using Spring.Context.Support; using Spring.Util; #endregion namespace Spring.Web.Services { /// <summary> /// Unit tests for the WebServiceProxyFactory class. /// </summary> /// <author>Bruno Baia</author> [TestFixture] public class WebServiceProxyFactoryTests { [Test] public void BailsWhenNotConfigured() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); Assert.Throws<ArgumentException>(() => wspf.AfterPropertiesSet()); } [Test] public void DocumentLiteralWithDefaultConfig() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); object[] typeAttrs = proxyType.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); Assert.IsTrue(typeAttrs.Length > 0); WebServiceBindingAttribute wsba = (WebServiceBindingAttribute)typeAttrs[0]; Assert.AreEqual("HelloWorldServiceSoap", wsba.Name); Assert.AreEqual("http://www.springframwework.net", wsba.Namespace); MethodInfo sayHelloWorldMethod = proxyType.GetMethod("SayHelloWorld"); Assert.IsNotNull(sayHelloWorldMethod); object[] sdmaAttrs = sayHelloWorldMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false); Assert.IsTrue(sdmaAttrs.Length > 0); SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)sdmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHelloWorld", sdma.Action); Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle); Assert.AreEqual(string.Empty, sdma.Binding); Assert.AreEqual(false, sdma.OneWay); Assert.AreEqual(string.Empty, sdma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace); Assert.AreEqual(string.Empty, sdma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", sdma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, sdma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void DocumentLiteralWithOneWay() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo logHelloWorldMethod = proxyType.GetMethod("LogHelloWorld"); Assert.IsNotNull(logHelloWorldMethod); object[] methodAttrs = logHelloWorldMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false); Assert.IsTrue(methodAttrs.Length > 0); SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)methodAttrs[0]; Assert.AreEqual("http://www.springframwework.net/LogHelloWorld", sdma.Action); Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle); Assert.AreEqual(string.Empty, sdma.Binding); Assert.AreEqual(true, sdma.OneWay); Assert.AreEqual(string.Empty, sdma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace); Assert.AreEqual(string.Empty, sdma.ResponseElementName); Assert.AreEqual(null, sdma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, sdma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void DocumentLiteralWithMessageName() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo logHelloMethod = proxyType.GetMethod("LogHello"); Assert.IsNotNull(logHelloMethod); object[] methodAttrs = logHelloMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false); Assert.IsTrue(methodAttrs.Length > 0); SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)methodAttrs[0]; Assert.AreEqual("http://www.springframwework.net/MyLogHello", sdma.Action); Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle); Assert.AreEqual(string.Empty, sdma.Binding); Assert.AreEqual(false, sdma.OneWay); Assert.AreEqual("MyLogHello", sdma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace); Assert.AreEqual("MyLogHelloResponse", sdma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", sdma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, sdma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void DocumentLiteralWithNamedOutParameter() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo sayHelloMethod = proxyType.GetMethod("SayHello"); Assert.IsNotNull(sayHelloMethod); object[] sdmaAttrs = sayHelloMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false); Assert.IsTrue(sdmaAttrs.Length > 0); SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)sdmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHello", sdma.Action); Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle); Assert.AreEqual(string.Empty, sdma.Binding); Assert.AreEqual(false, sdma.OneWay); Assert.AreEqual(string.Empty, sdma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace); Assert.AreEqual(string.Empty, sdma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", sdma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, sdma.Use); object[] xeAttrs = sayHelloMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(XmlElementAttribute), false); Assert.IsTrue(xeAttrs.Length > 0); XmlElementAttribute xea = (XmlElementAttribute)xeAttrs[0]; Assert.AreEqual("out", xea.ElementName); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void DocumentLiteralWithNamedOutArrayParameter() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo sayHelloArrayMethod = proxyType.GetMethod("SayHelloArray"); Assert.IsNotNull(sayHelloArrayMethod); object[] sdmaAttrs = sayHelloArrayMethod.GetCustomAttributes(typeof(SoapDocumentMethodAttribute), false); Assert.IsTrue(sdmaAttrs.Length > 0); SoapDocumentMethodAttribute sdma = (SoapDocumentMethodAttribute)sdmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHelloArray", sdma.Action); Assert.AreEqual(SoapParameterStyle.Wrapped, sdma.ParameterStyle); Assert.AreEqual(string.Empty, sdma.Binding); Assert.AreEqual(false, sdma.OneWay); Assert.AreEqual(string.Empty, sdma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", sdma.RequestNamespace); Assert.AreEqual(string.Empty, sdma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", sdma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, sdma.Use); object[] xaAttrs = sayHelloArrayMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(XmlArrayAttribute), false); Assert.IsTrue(xaAttrs.Length > 0); XmlArrayAttribute xaa = (XmlArrayAttribute)xaAttrs[0]; Assert.AreEqual("out", xaa.ElementName); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void RpcLiteralWithNamedOutParameter() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/rpc-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo sayHelloMethod = proxyType.GetMethod("SayHello"); Assert.IsNotNull(sayHelloMethod); object[] srmaAttrs = sayHelloMethod.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false); Assert.IsTrue(srmaAttrs.Length > 0); SoapRpcMethodAttribute srma = (SoapRpcMethodAttribute)srmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHello", srma.Action); Assert.AreEqual(string.Empty, srma.Binding); Assert.AreEqual(false, srma.OneWay); Assert.AreEqual(string.Empty, srma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", srma.RequestNamespace); Assert.AreEqual(string.Empty, srma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", srma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, srma.Use); object[] xeAttrs = sayHelloMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(XmlElementAttribute), false); Assert.IsTrue(xeAttrs.Length > 0); XmlElementAttribute xea = (XmlElementAttribute)xeAttrs[0]; Assert.AreEqual("out", xea.ElementName); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void RpcLiteralWithNamedOutArrayParameter() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/rpc-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo sayHelloArrayMethod = proxyType.GetMethod("SayHelloArray"); Assert.IsNotNull(sayHelloArrayMethod); object[] srmaAttrs = sayHelloArrayMethod.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false); Assert.IsTrue(srmaAttrs.Length > 0); SoapRpcMethodAttribute srma = (SoapRpcMethodAttribute)srmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHelloArray", srma.Action); Assert.AreEqual(string.Empty, srma.Binding); Assert.AreEqual(false, srma.OneWay); Assert.AreEqual(string.Empty, srma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", srma.RequestNamespace); Assert.AreEqual(string.Empty, srma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", srma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, srma.Use); object[] xaAttrs = sayHelloArrayMethod.ReturnTypeCustomAttributes.GetCustomAttributes(typeof(XmlArrayAttribute), false); Assert.IsTrue(xaAttrs.Length > 0); XmlArrayAttribute xaa = (XmlArrayAttribute)xaAttrs[0]; Assert.AreEqual("out", xaa.ElementName); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void RpcLiteralWithDefaultConfig() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/rpc-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); object[] typeAttrs = proxyType.GetCustomAttributes(typeof(WebServiceBindingAttribute), false); Assert.IsTrue(typeAttrs.Length > 0); WebServiceBindingAttribute wsba = (WebServiceBindingAttribute)typeAttrs[0]; Assert.AreEqual("HelloWorldServiceSoap", wsba.Name); Assert.AreEqual("http://www.springframwework.net", wsba.Namespace); MethodInfo sayHelloWorldMethod = proxyType.GetMethod("SayHelloWorld"); Assert.IsNotNull(sayHelloWorldMethod); object[] srmaAttrs = sayHelloWorldMethod.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false); Assert.IsTrue(srmaAttrs.Length > 0); SoapRpcMethodAttribute srma = (SoapRpcMethodAttribute)srmaAttrs[0]; Assert.AreEqual("http://www.springframwework.net/SayHelloWorld", srma.Action); Assert.AreEqual(string.Empty, srma.Binding); Assert.AreEqual(false, srma.OneWay); Assert.AreEqual(string.Empty, srma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", srma.RequestNamespace); Assert.AreEqual(string.Empty, srma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", srma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, srma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void RpcLiteralWithOneWay() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/rpc-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo logHelloWorldMethod = proxyType.GetMethod("LogHelloWorld"); Assert.IsNotNull(logHelloWorldMethod); object[] methodAttrs = logHelloWorldMethod.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false); Assert.IsTrue(methodAttrs.Length > 0); SoapRpcMethodAttribute srma = (SoapRpcMethodAttribute)methodAttrs[0]; Assert.AreEqual("http://www.springframwework.net/LogHelloWorld", srma.Action); Assert.AreEqual(string.Empty, srma.Binding); Assert.AreEqual(true, srma.OneWay); Assert.AreEqual(string.Empty, srma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", srma.RequestNamespace); Assert.AreEqual(string.Empty, srma.ResponseElementName); Assert.AreEqual(null, srma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, srma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void RpcLiteralWithMessageName() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/rpc-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); MethodInfo logHelloMethod = proxyType.GetMethod("LogHello"); Assert.IsNotNull(logHelloMethod); object[] methodAttrs = logHelloMethod.GetCustomAttributes(typeof(SoapRpcMethodAttribute), false); Assert.IsTrue(methodAttrs.Length > 0); SoapRpcMethodAttribute srma = (SoapRpcMethodAttribute)methodAttrs[0]; Assert.AreEqual("http://www.springframwework.net/MyLogHello", srma.Action); Assert.AreEqual(string.Empty, srma.Binding); Assert.AreEqual(false, srma.OneWay); Assert.AreEqual(string.Empty, srma.RequestElementName); Assert.AreEqual("http://www.springframwework.net", srma.RequestNamespace); Assert.AreEqual(string.Empty, srma.ResponseElementName); Assert.AreEqual("http://www.springframwework.net", srma.ResponseNamespace); Assert.AreEqual(SoapBindingUse.Literal, srma.Use); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void WrapProxyType() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ProxyType = typeof(FakeProxyClass); wspf.ServiceInterface = typeof(IHelloWorld); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void ConfigureSoapHttpClientProtocolWithServiceUri() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/configurableFactory.xml"); ContextRegistry.Clear(); ContextRegistry.RegisterContext(ctx); object proxy = ctx.GetObject("withServiceUri"); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); SoapHttpClientProtocol shcp = proxy as SoapHttpClientProtocol; Assert.AreEqual("http://www.springframework.org/", shcp.Url); Assert.AreEqual(10000, shcp.Timeout); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void ConfigureSoapHttpClientProtocolWithProxyType() { IApplicationContext ctx = new XmlApplicationContext("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/configurableFactory.xml"); ContextRegistry.Clear(); ContextRegistry.RegisterContext(ctx); object proxy = ctx.GetObject("withProxyType"); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); SoapHttpClientProtocol shcp = proxy as SoapHttpClientProtocol; Assert.AreEqual("http://www.springframework.org/", shcp.Url); Assert.AreEqual(10000, shcp.Timeout); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } [Test] public void UseCustomClientProtocolType() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new AssemblyResource("assembly://Spring.Services.Tests/Spring.Data.Spring.Web.Services/document-literal.wsdl"); wspf.ServiceInterface = typeof(IHelloWorld); wspf.WebServiceProxyBaseType = typeof(CustomClientProtocol); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IHelloWorld); Assert.IsTrue(proxy is SoapHttpClientProtocol); Assert.IsTrue(proxy is CustomClientProtocol); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } #region NestedSchema [Test] public void NestedSchema() { WebServiceProxyFactory wspf = new WebServiceProxyFactory(); // cf Post Build Events wspf.ServiceUri = new FileSystemResource("file://~/Spring/Web/Services/nestedSchema.wsdl"); wspf.ServiceInterface = typeof(INestedSchema); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is INestedSchema); Assert.IsTrue(proxy is SoapHttpClientProtocol); // Try to instantiate the proxy type ObjectUtils.InstantiateType(proxyType); } public interface INestedSchema { string testMethod(UserCredentials userCredentials); } public class UserCredentials { } #endregion public void WcfBasicHttpBinding() { using (ServiceHost host = new ServiceHost(typeof(WcfServiceImpl), new Uri("http://localhost:8000/WcfBasicHttpBinding/Service"))) { host.AddServiceEndpoint(typeof(IWcfService), new BasicHttpBinding(), string.Empty); ServiceMetadataBehavior smb = new ServiceMetadataBehavior(); smb.HttpGetEnabled = true; host.Description.Behaviors.Add(smb); host.Open(); WebServiceProxyFactory wspf = new WebServiceProxyFactory(); wspf.ServiceUri = new UrlResource("http://localhost:8000/WcfBasicHttpBinding/Service"); wspf.ServiceInterface = typeof(IWcfService); wspf.AfterPropertiesSet(); object proxy = wspf.GetObject(); Assert.IsNotNull(proxy); Type proxyType = proxy.GetType(); Assert.IsTrue(proxy is IWcfService); Assert.IsTrue(proxy is SoapHttpClientProtocol); IWcfService srv = proxy as IWcfService; Assert.AreEqual("5", srv.WcfMethod(5)); } } [ServiceContract(Namespace="http://www.springframework.net/")] public interface IWcfService { [OperationContract] string WcfMethod(int count); } public class WcfServiceImpl : IWcfService { public string WcfMethod(int count) { return count.ToString(); } } #region Test Classes public interface IHelloWorld { string SayHelloWorld(); string SayHello(string name); string[] SayHelloArray(string name); void LogHelloWorld(); void LogHello(string name); } /// <summary> /// Fake Web Service proxy that does not implement any interface. /// </summary> /// <remarks> /// Note that methods matchs IHelloWorld interface methods. /// </remarks> [WebServiceBinding(Name="FakeWebService")] public class FakeProxyClass : SoapHttpClientProtocol { public FakeProxyClass() { this.Url = "http://www.fcporto.pt/"; } public string SayHelloWorld() { return "Hello World !"; } public string SayHello(string name) { return String.Format("Hello {0} !", name); } public string[] SayHelloArray(string name) { return new string[] { "Hello ", name, " !" }; } public void LogHelloWorld() { } public void LogHello(string name) { } } public class CustomClientProtocol : SoapHttpClientProtocol { } #endregion } }
//--------------------------------------------------------------------------------------------- // Torque Game Builder // Copyright (C) GarageGames.com, Inc. //--------------------------------------------------------------------------------------------- $AlignTools::Horizontal = 0; $AlignTools::Vertical = 1; $AlignTools::Left = -1; $AlignTools::Right = 1; $AlignTools::Top = -1; $AlignTools::Bottom = 1; $AlignTools::Center = 0; function AlignTools::sort( %objects, %side, %dir ) { // Set the sort position for each object. %count = %objects.getCount(); for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %position = getWord( %object.getPosition(), %dir ); %halfSize = getWord( %object.getSize(), %dir ) * 0.5; %object.sortPos = %position + ( %halfSize * %side ); } // Selection sort by sortPos. for( %i = 0; %i < %count - 1; %i++ ) { %min = %i; for( %j = %i + 1; %j < %count; %j++ ) { %objMin = %objects.getObject( %min ); %obj = %objects.getObject( %j ); if( %obj.sortPos < %objMin.sortPos ) %min = %j; } %objMin = %objects.getObject( %min ); %obj = %objects.getObject( %i ); %objects.reorderChild( %objMin, %obj ); } } function AlignTools::deleteSorted( %objects ) { // Clear the sortPos field. %count = %objects.getCount(); for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %object.sortPos = ""; } } function AlignTools::align( %objects, %side, %dir ) { %objectPos = getWord( %objects.getPosition(), %dir ); %halfSize = getWord( %objects.getSize(), %dir ) * 0.5; %alignPos = %objectPos + ( %halfSize * %side ); AlignTools::alignToPosition( %objects, %side, %dir, %alignPos ); } function AlignTools::alignToCamera( %objects, %scenegraph, %side, %dir ) { %camPos = getWord( %scenegraph.cameraPosition, %dir ); %camHalfSize = getWord( %scenegraph.cameraSize, %dir ) * 0.5; %alignPos = %camPos + ( %camHalfSize * %side ); AlignTools::alignToPosition( %objects, %side, %dir, %alignPos ); } function AlignTools::alignToPosition( %objects, %side, %dir, %alignPos ) { %count = %objects.getCount(); for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %position = %object.getPosition(); %halfSize = getWord( %object.getSize(), %dir ) * 0.5; %newPosition = %alignPos + ( %halfSize * -%side ); %position = setWord( %position, %dir, %newPosition ); %object.setPosition( %position ); } } function AlignTools::distribute( %objects, %side, %dir ) { %count = %objects.getCount(); if( %count < 1 ) return; %alignLeftPos = %objects.getObject( 0 ).sortPos; %alignRightPos = %objects.getObject( %count - 1 ).sortPos; %spacing = ( %alignRightPos - %alignLeftPos ) / ( %count - 1 ); AlignTools::distributeToSpacing( %objects, %side, %dir, %spacing ); } function AlignTools::distributeToCamera( %objects, %scenegraph, %side, %dir ) { %count = %objects.getCount(); if( %count < 2 ) return; // Grab the camera bounds. %camPos = getWord( %scenegraph.cameraPosition, %dir ); %camHalfSize = getWord( %scenegraph.cameraSize, %dir ) * 0.5; %leftCam = %camPos - %camHalfSize; %rightCam = %camPos + %camHalfSize; // Set the left/top most object to the left/top of the camera. %firstObj = %objects.getObject( 0 ); %firstPos = getWord( %firstObj.position, %dir ); %firstHalfSize = getWord( %firstObj.size, %dir ) * 0.5; %firstNewPos = %leftCam + %firstHalfSize; %diff = %firstNewPos - %firstPos; %firstObj.position = setWord( %firstObj.position, %dir, %firstNewPos ); %firstObj.sortPos += %diff; // Set the right/bottom most object to the right/bottom of the camera. %lastObj = %objects.getObject( %count - 1 ); %lastPos = getWord( %lastObj.position, %dir ); %lastHalfSize = getWord( %lastObj.size, %dir ) * 0.5; %lastNewPos = %rightCam - %lastHalfSize; %diff = %lastNewPos - %lastPos; %lastObj.position = setWord( %lastObj.position, %dir, %lastNewPos ); %lastObj.sortPos += %diff; %spacing = ( %lastObj.sortPos - %firstObj.sortPos ) / ( %count - 1 ); AlignTools::distributeToSpacing( %objects, %side, %dir, %spacing ); } function AlignTools::distributeToSpacing( %objects, %side, %dir, %spacing ) { %count = %objects.getCount(); for( %i = 1; %i < %count - 1; %i++ ) { %prevObject = %objects.getObject( %i - 1 ); %object = %objects.getObject( %i ); %space = %object.sortPos - %prevObject.sortPos; %diff = %spacing - %space; %newPos = getWord( %object.position, %dir ) + %diff; %object.position = setWord( %object.position, %dir, %newPos ); %object.sortPos += %diff; } } function AlignTools::matchSize( %objects, %dir ) { if( %dir == 2 ) { AlignTools::matchSize( %objects, 0 ); AlignTools::matchSize( %objects, 1 ); return; } // Find the biggest object. %count = %objects.getCount(); for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %newSize = getWord( %object.size, %dir ); if( ( %biggest $= "" ) || ( %newSize > %biggest ) ) %biggest = %newSize; } AlignTools::matchSizeToAmount( %objects, %dir, %biggest ); } function AlignTools::matchSizeToCamera( %objects, %scenegraph, %dir ) { if( %dir == 2 ) { AlignTools::matchSizeToCamera( %objects, %scenegraph, 0 ); AlignTools::matchSizeToCamera( %objects, %scenegraph, 1 ); return; } %size = getWord( %scenegraph.cameraSize, %dir ); AlignTools::matchSizeToAmount( %objects, %dir, %size ); } function AlignTools::matchSizeToAmount( %objects, %dir, %size ) { %count = %objects.getCount(); for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %object.size = setWord( %object.size, %dir, %size ); } } function AlignTools::space( %objects, %dir ) { %count = %objects.getCount(); if( %count < 2 ) return; // Total space is the entire amount of space taken up. %firstObject = %objects.getObject( 0 ); %left = getWord( %firstObject.position, %dir ) - ( getWord( %firstObject.size, %dir ) * 0.5 ); %lastObject = %objects.getObject( %count - 1 ); %right = getWord( %lastObject.position, %dir ) + ( getWord( %lastObject.size, %dir ) * 0.5 ); %totalSpace = %right - %left; // Occupied space is the amount of space taken up by the objects. %occupiedSpace = 0; for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %space = getWord( %object.size, %dir ); %occupiedSpace += %space; } // Spacing is the amount of space to put between each object. %spacing = ( %totalSpace - %occupiedSpace ) / ( %count - 1 ); AlignTools::spaceToAmount( %objects, %dir, %spacing ); } function AlignTools::spaceToCamera( %objects, %scenegraph, %dir ) { %count = %objects.getCount(); if( %count < 2 ) return; // Grab the camera bounds. %camPos = getWord( %scenegraph.cameraPosition, %dir ); %camHalfSize = getWord( %scenegraph.cameraSize, %dir ) * 0.5; %leftCam = %camPos - %camHalfSize; %rightCam = %camPos + %camHalfSize; // Set the left/top most object to the left/top of the camera. %firstObj = %objects.getObject( 0 ); %firstPos = getWord( %firstObj.position, %dir ); %firstHalfSize = getWord( %firstObj.size, %dir ) * 0.5; %firstNewPos = %leftCam + %firstHalfSize; %diff = %firstNewPos - %firstPos; %firstObj.position = setWord( %firstObj.position, %dir, %firstNewPos ); %firstObj.sortPos += %diff; // Set the right/bottom most object to the right/bottom of the camera. %lastObj = %objects.getObject( %count - 1 ); %lastPos = getWord( %lastObj.position, %dir ); %lastHalfSize = getWord( %lastObj.size, %dir ) * 0.5; %lastNewPos = %rightCam - %lastHalfSize; %diff = %lastNewPos - %lastPos; %lastObj.position = setWord( %lastObj.position, %dir, %lastNewPos ); %lastObj.sortPos += %diff; %totalSpace = %rightCam - %leftCam; // Occupied space is the amount of space taken up by the objects. %occupiedSpace = 0; for( %i = 0; %i < %count; %i++ ) { %object = %objects.getObject( %i ); %space = getWord( %object.size, %dir ); %occupiedSpace += %space; } // Spacing is the amount of space to put between each object. %spacing = ( %totalSpace - %occupiedSpace ) / ( %count - 1 ); AlignTools::spaceToAmount( %objects, %dir, %spacing ); } function AlignTools::spaceToAmount( %objects, %dir, %spacing ) { %count = %objects.getCount(); for( %i = 1; %i < %count - 1; %i++ ) { %prevObject = %objects.getObject( %i - 1 ); %object = %objects.getObject( %i ); %pos = getWord( %prevObject.position, %dir ); %pos += getWord( %prevObject.size, %dir ) * 0.5; %pos += %spacing; %pos += getWord( %object.size, %dir ) * 0.5; %object.position = setWord( %object.position, %dir, %pos ); } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <[email protected]> using UnityEngine; using System.Collections.Generic; using UnityEditor; using System; namespace AmplifyShaderEditor { public class PaletteFilterData { public bool Visible; public bool HasCommunityData; public List<ContextMenuItem> Contents; public PaletteFilterData( bool visible ) { Visible = visible; Contents = new List<ContextMenuItem>(); } } public class PaletteParent : MenuParent { private const float ItemSize = 18; public delegate void OnPaletteNodeCreate( Type type, string name ); public event OnPaletteNodeCreate OnPaletteNodeCreateEvt; private string m_searchFilterStr = "Search"; protected string m_searchFilterControl = "SHADERNAMETEXTFIELDCONTROLNAME"; protected bool m_focusOnSearch = false; protected bool m_defaultCategoryVisible = false; protected List<ContextMenuItem> m_allItems; protected List<ContextMenuItem> m_currentItems; protected Dictionary<string, PaletteFilterData> m_currentCategories; private bool m_forceUpdate = true; protected string m_searchFilter; private float m_searchLabelSize = -1; private GUIStyle m_buttonStyle; private GUIStyle m_foldoutStyle; protected int m_validButtonId = 0; protected int m_initialSeparatorAmount = 1; private Vector2 _currScrollBarDims = new Vector2( 1, 1 ); public PaletteParent( List<ContextMenuItem> items, float x, float y, float width, float height, string name, MenuAnchor anchor = MenuAnchor.NONE, MenuAutoSize autoSize = MenuAutoSize.NONE ) : base( x, y, width, height, name, anchor, autoSize ) { m_searchFilter = string.Empty; m_currentCategories = new Dictionary<string, PaletteFilterData>(); m_allItems = new List<ContextMenuItem>(); m_currentItems = new List<ContextMenuItem>(); for ( int i = 0; i < items.Count; i++ ) { m_allItems.Add( items[ i ] ); } } public virtual void OnEnterPressed() { } public virtual void OnEscapePressed() { } public void SortElements() { m_allItems.Sort( ( x, y ) => x.Category.CompareTo( y.Category ) ); } public void FireNodeCreateEvent( Type type, string name ) { OnPaletteNodeCreateEvt( type, name ); } public override void Draw( Rect parentPosition, Vector2 mousePosition, int mouseButtonId, bool hasKeyboadFocus ) { base.Draw( parentPosition, mousePosition, mouseButtonId, hasKeyboadFocus ); if ( m_searchLabelSize < 0 ) { m_searchLabelSize = GUI.skin.label.CalcSize( new GUIContent( m_searchFilterStr ) ).x; } if ( m_foldoutStyle == null ) { m_foldoutStyle = new GUIStyle( GUI.skin.GetStyle( "foldout" ) ); m_foldoutStyle.fontStyle = FontStyle.Bold; } if ( m_buttonStyle == null ) { m_buttonStyle = UIUtils.CurrentWindow.CustomStylesInstance.Label; } GUILayout.BeginArea( m_transformedArea, m_content, m_style ); { for ( int i = 0; i < m_initialSeparatorAmount; i++ ) { EditorGUILayout.Separator(); } if ( Event.current.type == EventType.keyDown ) { KeyCode key = Event.current.keyCode; if ( key == KeyCode.Return || key == KeyCode.KeypadEnter ) OnEnterPressed(); if ( key == KeyCode.Escape ) OnEscapePressed(); if ( m_isMouseInside || hasKeyboadFocus ) { if ( key == ShortcutsManager.ScrollUpKey ) { m_currentScrollPos.y -= 10; if ( m_currentScrollPos.y < 0 ) { m_currentScrollPos.y = 0; } Event.current.Use(); } if ( key == ShortcutsManager.ScrollDownKey ) { m_currentScrollPos.y += 10; Event.current.Use(); } } } float width = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = m_searchLabelSize; EditorGUI.BeginChangeCheck(); { GUI.SetNextControlName( m_searchFilterControl ); m_searchFilter = EditorGUILayout.TextField( m_searchFilterStr, m_searchFilter ); if ( m_focusOnSearch ) { m_focusOnSearch = false; EditorGUI.FocusTextInControl( m_searchFilterControl ); } } if ( EditorGUI.EndChangeCheck() ) m_forceUpdate = true; EditorGUIUtility.labelWidth = width; bool usingSearchFilter = ( m_searchFilter.Length == 0 ); _currScrollBarDims.x = m_transformedArea.width; _currScrollBarDims.y = m_transformedArea.height; m_currentScrollPos = EditorGUILayout.BeginScrollView( m_currentScrollPos, GUILayout.Width( 0 ), GUILayout.Height( 0 ) ); { if ( m_forceUpdate ) { m_forceUpdate = false; m_currentItems.Clear(); m_currentCategories.Clear(); if ( usingSearchFilter ) { for ( int i = 0; i < m_allItems.Count; i++ ) { m_currentItems.Add( m_allItems[ i ] ); if ( !m_currentCategories.ContainsKey( m_allItems[ i ].Category ) ) { m_currentCategories.Add( m_allItems[ i ].Category, new PaletteFilterData( m_defaultCategoryVisible ) ); m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData = m_allItems[ i ].NodeAttributes.FromCommunity || m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData; } m_currentCategories[ m_allItems[ i ].Category ].Contents.Add( m_allItems[ i ] ); } } else { for ( int i = 0; i < m_allItems.Count; i++ ) { if ( m_allItems[ i ].Name.IndexOf( m_searchFilter, StringComparison.InvariantCultureIgnoreCase ) >= 0 || m_allItems[ i ].Category.IndexOf( m_searchFilter, StringComparison.InvariantCultureIgnoreCase ) >= 0 ) { m_currentItems.Add( m_allItems[ i ] ); if ( !m_currentCategories.ContainsKey( m_allItems[ i ].Category ) ) { m_currentCategories.Add( m_allItems[ i ].Category, new PaletteFilterData( m_defaultCategoryVisible ) ); m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData = m_allItems[ i ].NodeAttributes.FromCommunity || m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData; } m_currentCategories[ m_allItems[ i ].Category ].Contents.Add( m_allItems[ i ] ); } } } var categoryEnumerator = m_currentCategories.GetEnumerator(); while ( categoryEnumerator.MoveNext() ) { categoryEnumerator.Current.Value.Contents.Sort( ( x, y ) => x.CompareTo( y, usingSearchFilter ) ); } } float currPos = 0; var enumerator = m_currentCategories.GetEnumerator(); while ( enumerator.MoveNext() ) { var current = enumerator.Current; bool visible = GUILayout.Toggle( current.Value.Visible, current.Key, m_foldoutStyle ); if ( m_validButtonId == mouseButtonId ) { current.Value.Visible = visible; } currPos += ItemSize; if ( m_searchFilter.Length > 0 || current.Value.Visible ) { for ( int i = 0; i < current.Value.Contents.Count; i++ ) { if ( !IsItemVisible( currPos ) ) { // Invisible GUILayout.Space( ItemSize ); } else { // Visible EditorGUILayout.BeginHorizontal(); GUILayout.Space( 16 ); if ( m_isMouseInside ) { if ( CheckButton( current.Value.Contents[ i ].ItemUIContent, m_buttonStyle, mouseButtonId ) ) { int controlID = GUIUtility.GetControlID( FocusType.Passive ); GUIUtility.hotControl = controlID; OnPaletteNodeCreateEvt( current.Value.Contents[ i ].NodeType, current.Value.Contents[ i ].Name ); } } else { GUILayout.Label( current.Value.Contents[ i ].ItemUIContent, m_buttonStyle ); } EditorGUILayout.EndHorizontal(); } currPos += ItemSize; } } } } EditorGUILayout.EndScrollView(); } GUILayout.EndArea(); } public void DumpAvailableNodes( bool fromCommunity, string pathname ) { string noTOCHeader = "__NOTOC__\n"; string nodesHeader = "== Available Node Categories ==\n"; string InitialCategoriesFormat = "[[#{0}|{0}]]<br>\n"; string InitialCategories = string.Empty; string CurrentCategoryFormat = "\n== {0} ==\n\n"; string NodesFootFormat = "[[Unity Products:Amplify Shader Editor/{0} | Learn More]] -\n[[#Top|Back to Categories]]\n"; string NodesFootFormatSep = "----\n"; string OverallFoot = "[[Category:Nodes]]"; string NodeInfoBeginFormat = "{| cellpadding=\"10\"\n"; string nodeInfoBodyFormat = "|- style=\"vertical-align:top;\"\n| http://amplify.pt/Nodes/{0}.jpg\n| [[Unity Products:Amplify Shader Editor/{1} | <span style=\"font-size: 120%;\"><span id=\"{2}\"></span>'''{2}'''<span> ]] <br> {3}\n"; string NodeInfoEndFormat = "|}\n"; string nodesInfo = string.Empty; var enumerator = m_currentCategories.GetEnumerator(); while ( enumerator.MoveNext() ) { var current = enumerator.Current; if ( fromCommunity && current.Value.HasCommunityData || !fromCommunity ) { InitialCategories += string.Format( InitialCategoriesFormat, current.Key ); nodesInfo += string.Format( CurrentCategoryFormat, current.Key ); int count = current.Value.Contents.Count; for ( int i = 0; i < count; i++ ) { if ( ( fromCommunity && current.Value.Contents[ i ].NodeAttributes.FromCommunity ) || ( !fromCommunity && !current.Value.Contents[ i ].NodeAttributes.FromCommunity ) ) { string nodeFullName = current.Value.Contents[ i ].Name; string pictureFilename = UIUtils.ReplaceInvalidStrings( nodeFullName ); string pageFilename = UIUtils.RemoveWikiInvalidCharacters( pictureFilename ); pictureFilename = UIUtils.RemoveInvalidCharacters( pictureFilename ); string nodeDescription = current.Value.Contents[ i ].ItemUIContent.tooltip; string nodeInfoBody = string.Format( nodeInfoBodyFormat, pictureFilename, pageFilename, nodeFullName, nodeDescription ); string nodeInfoFoot = string.Format( NodesFootFormat, pageFilename ); nodesInfo += ( NodeInfoBeginFormat + nodeInfoBody + NodeInfoEndFormat + nodeInfoFoot ); if ( i != ( count - 1 ) ) { nodesInfo += NodesFootFormatSep; } } } } } string finalText = noTOCHeader + nodesHeader + InitialCategories + nodesInfo + OverallFoot; if ( !System.IO.Directory.Exists( pathname ) ) { System.IO.Directory.CreateDirectory( pathname ); } // Save file string nodesPathname = pathname + ( fromCommunity ? "AvailableNodesFromCommunity.txt" : "AvailableNodes.txt" ); Debug.Log( " Creating nodes file at " + nodesPathname ); IOUtils.SaveTextfileToDisk( finalText, nodesPathname, false ); } public virtual bool CheckButton( GUIContent content, GUIStyle style, int buttonId ) { if ( buttonId != m_validButtonId ) { GUILayout.Label( content, style ); return false; } return GUILayout.RepeatButton( content, style ); } public void FillList( ref List<ContextMenuItem> list ) { list.Clear(); int count = m_allItems.Count; for ( int i = 0; i < count; i++ ) { list.Add( m_allItems[ i ] ); } } public Dictionary<string,PaletteFilterData> BuildFullList() { //Only need to build if search filter is active and list is set according to it if ( m_searchFilter.Length > 0 || !m_isActive || m_currentCategories.Count == 0 ) { m_currentItems.Clear(); m_currentCategories.Clear(); for ( int i = 0; i < m_allItems.Count; i++ ) { if ( m_allItems[ i ].Name.IndexOf( m_searchFilter, StringComparison.InvariantCultureIgnoreCase ) >= 0 || m_allItems[ i ].Category.IndexOf( m_searchFilter, StringComparison.InvariantCultureIgnoreCase ) >= 0 ) { m_currentItems.Add( m_allItems[ i ] ); if ( !m_currentCategories.ContainsKey( m_allItems[ i ].Category ) ) { m_currentCategories.Add( m_allItems[ i ].Category, new PaletteFilterData( m_defaultCategoryVisible ) ); m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData = m_allItems[ i ].NodeAttributes.FromCommunity || m_currentCategories[ m_allItems[ i ].Category ].HasCommunityData; } m_currentCategories[ m_allItems[ i ].Category ].Contents.Add( m_allItems[ i ] ); } } var categoryEnumerator = m_currentCategories.GetEnumerator(); while ( categoryEnumerator.MoveNext() ) { categoryEnumerator.Current.Value.Contents.Sort( ( x, y ) => x.CompareTo( y, false ) ); } //mark to force update and take search filter into account m_forceUpdate = true; } return m_currentCategories; } private bool IsItemVisible( float currPos ) { if ( ( currPos < m_currentScrollPos.y && ( currPos + ItemSize ) < m_currentScrollPos.y ) || ( currPos > ( m_currentScrollPos.y + _currScrollBarDims.y ) && ( currPos + ItemSize ) > ( m_currentScrollPos.y + _currScrollBarDims.y ) ) ) { return false; } return true; } public override void Destroy() { base.Destroy(); m_allItems.Clear(); m_allItems = null; m_currentItems.Clear(); m_currentItems = null; m_currentCategories.Clear(); m_currentCategories = null; OnPaletteNodeCreateEvt = null; m_buttonStyle = null; m_foldoutStyle = null; } public List<ContextMenuItem> AllNodes { get { return m_allItems; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Job Accounts. /// Contains operations to: Create, Retrieve, Update, and Delete Job /// Accounts /// </summary> internal partial class JobAccountOperations : IServiceOperations<SqlManagementClient>, IJobAccountOperations { /// <summary> /// Initializes a new instance of the JobAccountOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal JobAccountOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new Azure SQL Job Account or updating an existing /// Azure SQL Job Account. To determine the status of the operation /// call GetJobAccountOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } if (parameters.Properties.DatabaseId == null) { throw new ArgumentNullException("parameters.Properties.DatabaseId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject jobAccountCreateOrUpdateParametersValue = new JObject(); requestDoc = jobAccountCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); jobAccountCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["databaseId"] = parameters.Properties.DatabaseId; jobAccountCreateOrUpdateParametersValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } jobAccountCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue2["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey2, tagsValue2); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Begins deleting the Azure SQL Job Account with the given name. To /// determine the status of the operation call /// GetJobAccountOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be deleted. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> BeginDeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Job /// Account. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string jobAccountName, JobAccountCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse response = await client.JobAccounts.BeginCreateOrUpdateAsync(resourceGroupName, serverName, jobAccountName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Creates a new Azure SQL Job Account or updates an existing Azure /// SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Job Database Server that the /// Job Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be created or /// updated. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse response = await client.JobAccounts.BeginDeleteAsync(resourceGroupName, serverName, jobAccountName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); JobAccountOperationResponse result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.JobAccounts.GetJobAccountOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Returns information about an Azure SQL Job Account. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Account is hosted in. /// </param> /// <param name='jobAccountName'> /// Required. The name of the Azure SQL Job Account to be retrieved. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a Get Azure Sql Job Account request. /// </returns> public async Task<JobAccountGetResponse> GetAsync(string resourceGroupName, string serverName, string jobAccountName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (jobAccountName == null) { throw new ArgumentNullException("jobAccountName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("jobAccountName", jobAccountName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts/"; url = url + Uri.EscapeDataString(jobAccountName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure Sql Job Account create or update /// operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql Job Account operations. /// </returns> public async Task<JobAccountOperationResponse> GetJobAccountOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetJobAccountOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountOperationResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountOperationResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } JobAccount jobAccountInstance = new JobAccount(); result.JobAccount = jobAccountInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about Azure SQL Job Accounts. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server that the Job /// Accounts are hosted in. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Job Accounts request. /// </returns> public async Task<JobAccountListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/jobAccounts"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-05-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobAccountListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobAccountListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { JobAccount jobAccountInstance = new JobAccount(); result.JobAccounts.Add(jobAccountInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { JobAccountProperties propertiesInstance = new JobAccountProperties(); jobAccountInstance.Properties = propertiesInstance; JToken databaseIdValue = propertiesValue["databaseId"]; if (databaseIdValue != null && databaseIdValue.Type != JTokenType.Null) { string databaseIdInstance = ((string)databaseIdValue); propertiesInstance.DatabaseId = databaseIdInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); jobAccountInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); jobAccountInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); jobAccountInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); jobAccountInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); jobAccountInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Debugging { public class DataTipInfoGetterTests { private void Test(string markup, string expectedText = null) { TestSpanGetter(markup, (document, position, expectedSpan) => { var result = DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None).WaitAndGetResult(CancellationToken.None); Assert.Equal(expectedSpan, result.Span); Assert.Equal(expectedText, result.Text); }); } private void TestNoDataTip(string markup) { TestSpanGetter(markup, (document, position, expectedSpan) => { var result = DataTipInfoGetter.GetInfoAsync(document, position, CancellationToken.None).WaitAndGetResult(CancellationToken.None); Assert.True(result.IsDefault); }); } private void TestSpanGetter(string markup, Action<Document, int, TextSpan?> continuation) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(markup)) { var testHostDocument = workspace.Documents.Single(); var position = testHostDocument.CursorPosition.Value; var expectedSpan = testHostDocument.SelectedSpans.Any() ? testHostDocument.SelectedSpans.Single() : (TextSpan?)null; continuation( workspace.CurrentSolution.Projects.First().Documents.First(), position, expectedSpan); } } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestCSharpLanguageDebugInfoGetDataTipSpanAndText() { Test("class [|C$$|] { }"); Test("struct [|C$$|] { }"); Test("interface [|C$$|] { }"); Test("enum [|C$$|] { }"); Test("delegate void [|C$$|] ();"); // Without the space, that position is actually on the open paren. } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test1() { Test( @"class C { void Foo() { [|Sys$$tem|].Console.WriteLine(args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test2() { Test( @"class C { void Foo() { [|System$$.Console|].WriteLine(args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test3() { Test( @"class C { void Foo() { [|System.$$Console|].WriteLine(args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test4() { Test( @"class C { void Foo() { [|System.Con$$sole|].WriteLine(args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test5() { Test( @"class C { void Foo() { [|System.Console.Wri$$teLine|](args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test6() { TestNoDataTip( @"class C { void Foo() { [|System.Console.WriteLine|]$$(args); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test7() { Test( @"class C { void Foo() { System.Console.WriteLine($$[|args|]); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void Test8() { TestNoDataTip( @"class C { void Foo() { [|System.Console.WriteLine|](args$$); } }"); } [WpfFact] public void TestVar() { Test( @"class C { void Foo() { [|va$$r|] v = 0; } }", "int"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestVariableType() { Test( @"class C { void Foo() { [|in$$t|] i = 0; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestVariableIdentifier() { Test( @"class C { void Foo() { int [|$$i|] = 0; } }"); } [WorkItem(539910)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestLiterals() { Test( @"class C { void Foo() { int i = [|4$$2|]; } }", "int"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestNonExpressions() { TestNoDataTip( @"class C { void Foo() { int i = 42; }$$ }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestParameterIdentifier() { Test( @"class C { void Foo(int [|$$i|]) { } }"); } [WorkItem(942699)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestCatchIdentifier() { Test( @"class C { void Foo() { try { } catch (System.Exception [|$$e|]) { } } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestEvent() { Test( @"class C { event System.Action [|$$E|]; }"); Test( @"class C { event System.Action [|$$E|] { add { } remove { } } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestMethod() { Test( @"class C { int [|$$M|]() { } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestTypeParameter() { Test("class C<T, [|$$U|], V> { }"); Test( @"class C { void M<T, [|$$U|]>() { } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void UsingAlias() { Test( @"using [|$$S|] = Static; static class Static { }"); } [WorkItem(540921)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestForEachIdentifier() { Test( @"class C { void Foo(string[] args) { foreach (string [|$$s|] in args) { } } }"); } [WorkItem(546328)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestProperty() { Test( @"namespace ConsoleApplication16 { class C { public int [|$$foo|] { get; private set; } // hover over me public C() { this.foo = 1; } public int Foo() { return 2; // breakpoint here } } class Program { static void Main(string[] args) { new C().Foo(); } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips)] public void TestQueryIdentifier() { Test( // From @"class C { object Foo(string[] args) { return from [|$$a|] in args select a; } }"); Test( // Let @"class C { object Foo(string[] args) { return from a in args let [|$$b|] = ""END"" select a + b; } }"); Test( // Join @"class C { object Foo(string[] args) { return from a in args join [|$$b|] in args on a equals b; } }"); Test( // Join Into @"class C { object Foo(string[] args) { return from a in args join b in args on a equals b into [|$$c|]; } }"); Test( // Continuation @"class C { object Foo(string[] args) { return from a in args select a into [|$$b|] from c in b select c; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843)] public void TestConditionalAccessExpression() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ D D; }} class D {{ }} "; // One level. Test(string.Format(sourceTemplate, "[|Me?.$$B|]")); // Two levels. Test(string.Format(sourceTemplate, "[|Me?.$$B|].C")); Test(string.Format(sourceTemplate, "[|Me?.B.$$C|]")); Test(string.Format(sourceTemplate, "[|Me.$$B|]?.C")); Test(string.Format(sourceTemplate, "[|Me.B?.$$C|]")); Test(string.Format(sourceTemplate, "[|Me?.$$B|]?.C")); Test(string.Format(sourceTemplate, "[|Me?.B?.$$C|]")); // Three levels. Test(string.Format(sourceTemplate, "[|Me?.$$B|].C.D")); Test(string.Format(sourceTemplate, "[|Me?.B.$$C|].D")); Test(string.Format(sourceTemplate, "[|Me?.B.C.$$D|]")); Test(string.Format(sourceTemplate, "[|Me.$$B|]?.C.D")); Test(string.Format(sourceTemplate, "[|Me.B?.$$C|].D")); Test(string.Format(sourceTemplate, "[|Me.B?.C.$$D|]")); Test(string.Format(sourceTemplate, "[|Me.$$B|].C?.D")); Test(string.Format(sourceTemplate, "[|Me.B.$$C|]?.D")); Test(string.Format(sourceTemplate, "[|Me.B.C?.$$D|]")); Test(string.Format(sourceTemplate, "[|Me?.$$B|]?.C.D")); Test(string.Format(sourceTemplate, "[|Me?.B?.$$C|].D")); Test(string.Format(sourceTemplate, "[|Me?.B?.C.$$D|]")); Test(string.Format(sourceTemplate, "[|Me?.$$B|].C?.D")); Test(string.Format(sourceTemplate, "[|Me?.B.$$C|]?.D")); Test(string.Format(sourceTemplate, "[|Me?.B.C?.$$D|]")); Test(string.Format(sourceTemplate, "[|Me.$$B|]?.C?.D")); Test(string.Format(sourceTemplate, "[|Me.B?.$$C|]?.D")); Test(string.Format(sourceTemplate, "[|Me.B?.C?.$$D|]")); Test(string.Format(sourceTemplate, "[|Me?.$$B|]?.C?.D")); Test(string.Format(sourceTemplate, "[|Me?.B?.$$C|]?.D")); Test(string.Format(sourceTemplate, "[|Me?.B?.C?.$$D|]")); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingDataTips), WorkItem(1077843)] public void TestConditionalAccessExpression_Trivia() { var sourceTemplate = @" class A {{ B B; object M() {{ return {0}; }} }} class B {{ C C; }} class C {{ }} "; Test(string.Format(sourceTemplate, "/*1*/[|$$Me|]/*2*/?./*3*/B/*4*/?./*5*/C/*6*/")); Test(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/$$B|]/*4*/?./*5*/C/*6*/")); Test(string.Format(sourceTemplate, "/*1*/[|Me/*2*/?./*3*/B/*4*/?./*5*/$$C|]/*6*/")); } } }
/* * 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 OpenMetaverse; namespace OpenSim.Framework { /// <summary> /// Inventory Item - contains all the properties associated with an individual inventory piece. /// </summary> public class InventoryItemBase : InventoryNodeBase, ICloneable { /// <value> /// The inventory type of the item. This is slightly different from the asset type in some situations. /// </value> public int InvType { get { return m_invType; } set { m_invType = value; } } protected int m_invType; /// <value> /// The folder this item is contained in /// </value> public UUID Folder { get { return m_folder; } set { m_folder = value; } } protected UUID m_folder; /// <value> /// The creator of this item /// </value> public string CreatorId { get { return m_creatorId; } set { m_creatorId = value; } } protected string m_creatorId; /// <value> /// The CreatorId expressed as a UUID.tely /// </value> public UUID CreatorIdAsUuid { get { if (UUID.Zero == m_creatorIdAsUuid) { UUID.TryParse(CreatorId, out m_creatorIdAsUuid); } return m_creatorIdAsUuid; } } protected UUID m_creatorIdAsUuid = UUID.Zero; /// <summary> /// Extended creator information of the form <profile url>;<name> /// </summary> public string CreatorData // = <profile url>;<name> { get { return m_creatorData; } set { m_creatorData = value; } } protected string m_creatorData = string.Empty; /// <summary> /// Used by the DB layer to retrieve / store the entire user identification. /// The identification can either be a simple UUID or a string of the form /// uuid[;profile_url[;name]] /// </summary> public string CreatorIdentification { get { if (!string.IsNullOrEmpty(m_creatorData)) return m_creatorId + ';' + m_creatorData; else return m_creatorId; } set { if ((value == null) || (value != null && value == string.Empty)) { m_creatorData = string.Empty; return; } if (!value.Contains(";")) // plain UUID { m_creatorId = value; } else // <uuid>[;<endpoint>[;name]] { string name = "Unknown User"; string[] parts = value.Split(';'); if (parts.Length >= 1) m_creatorId = parts[0]; if (parts.Length >= 2) m_creatorData = parts[1]; if (parts.Length >= 3) name = parts[2]; m_creatorData += ';' + name; } } } /// <value> /// The description of the inventory item (must be less than 64 characters) /// </value> public string Description { get { return m_description; } set { m_description = value; } } protected string m_description = String.Empty; /// <value> /// /// </value> public uint NextPermissions { get { return m_nextPermissions; } set { m_nextPermissions = value; } } protected uint m_nextPermissions; /// <value> /// A mask containing permissions for the current owner (cannot be enforced) /// </value> public uint CurrentPermissions { get { return m_currentPermissions; } set { m_currentPermissions = value; } } protected uint m_currentPermissions; /// <value> /// /// </value> public uint BasePermissions { get { return m_basePermissions; } set { m_basePermissions = value; } } protected uint m_basePermissions; /// <value> /// /// </value> public uint EveryOnePermissions { get { return m_everyonePermissions; } set { m_everyonePermissions = value; } } protected uint m_everyonePermissions; /// <value> /// /// </value> public uint GroupPermissions { get { return m_groupPermissions; } set { m_groupPermissions = value; } } protected uint m_groupPermissions; /// <value> /// This is an enumerated value determining the type of asset (eg Notecard, Sound, Object, etc) /// </value> public int AssetType { get { return m_assetType; } set { m_assetType = value; } } protected int m_assetType; /// <value> /// The UUID of the associated asset on the asset server /// </value> public UUID AssetID { get { return m_assetID; } set { m_assetID = value; } } protected UUID m_assetID; /// <value> /// /// </value> public UUID GroupID { get { return m_groupID; } set { m_groupID = value; } } protected UUID m_groupID; /// <value> /// /// </value> public bool GroupOwned { get { return m_groupOwned; } set { m_groupOwned = value; } } protected bool m_groupOwned; /// <value> /// /// </value> public int SalePrice { get { return m_salePrice; } set { m_salePrice = value; } } protected int m_salePrice; /// <value> /// /// </value> public byte SaleType { get { return m_saleType; } set { m_saleType = value; } } protected byte m_saleType; /// <value> /// /// </value> public uint Flags { get { return m_flags; } set { m_flags = value; } } protected uint m_flags; /// <value> /// /// </value> public int CreationDate { get { return m_creationDate; } set { m_creationDate = value; } } protected int m_creationDate = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; public InventoryItemBase() { } public InventoryItemBase(UUID id) { ID = id; } public InventoryItemBase(UUID id, UUID owner) { ID = id; Owner = owner; } public object Clone() { return MemberwiseClone(); } } }
// 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.Diagnostics.Contracts; using System.Net; using System.Net.Sockets; using System.Runtime; using System.Text; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal class SocketConnection : IConnection { static AsyncCallback s_onReceiveCompleted; static EventHandler<SocketAsyncEventArgs> s_onReceiveAsyncCompleted; static EventHandler<SocketAsyncEventArgs> s_onSocketSendCompleted; // common state private Socket _socket; private TimeSpan _asyncSendTimeout; private TimeSpan _readFinTimeout; private TimeSpan _asyncReceiveTimeout; // Socket.SendTimeout/Socket.ReceiveTimeout only work with the synchronous API calls and therefore they // do not get updated when asynchronous Send/Read operations are performed. In order to make sure we // Set the proper timeouts on the Socket itself we need to keep these two additional fields. private TimeSpan _socketSyncSendTimeout; private TimeSpan _socketSyncReceiveTimeout; private CloseState _closeState; private bool _isShutdown; private bool _noDelay = false; private bool _aborted; // close state private TimeoutHelper _closeTimeoutHelper; private static Action<object> s_onWaitForFinComplete = new Action<object>(OnWaitForFinComplete); // read state private int _asyncReadSize; private SocketAsyncEventArgs _asyncReadEventArgs; private byte[] _readBuffer; private int _asyncReadBufferSize; private object _asyncReadState; private Action<object> _asyncReadCallback; private Exception _asyncReadException; private bool _asyncReadPending; // write state private SocketAsyncEventArgs _asyncWriteEventArgs; private object _asyncWriteState; private Action<object> _asyncWriteCallback; private Exception _asyncWriteException; private bool _asyncWritePending; private IOTimer<SocketConnection> _receiveTimer; private static Action<object> s_onReceiveTimeout; private IOTimer<SocketConnection> _sendTimer; private static Action<object> s_onSendTimeout; private string _timeoutErrorString; private TransferOperation _timeoutErrorTransferOperation; private IPEndPoint _remoteEndpoint; private ConnectionBufferPool _connectionBufferPool; private string _remoteEndpointAddress; public SocketConnection(Socket socket, ConnectionBufferPool connectionBufferPool, bool autoBindToCompletionPort) { _connectionBufferPool = connectionBufferPool ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(connectionBufferPool)); _socket = socket ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(socket)); _closeState = CloseState.Open; _readBuffer = connectionBufferPool.Take(); _asyncReadBufferSize = _readBuffer.Length; _socket.SendBufferSize = _socket.ReceiveBufferSize = _asyncReadBufferSize; _asyncSendTimeout = _asyncReceiveTimeout = TimeSpan.MaxValue; _socketSyncSendTimeout = _socketSyncReceiveTimeout = TimeSpan.MaxValue; _remoteEndpoint = null; if (autoBindToCompletionPort) { _socket.UseOnlyOverlappedIO = false; } // In SMSvcHost, sockets must be duplicated to the target process. Binding a handle to a completion port // prevents any duplicated handle from ever binding to a completion port. The target process is where we // want to use completion ports for performance. This means that in SMSvcHost, socket.UseOnlyOverlappedIO // must be set to true to prevent completion port use. if (_socket.UseOnlyOverlappedIO) { // Init BeginRead state if (s_onReceiveCompleted == null) { s_onReceiveCompleted = Fx.ThunkCallback(new AsyncCallback(OnReceiveCompleted)); } } } public int AsyncReadBufferSize { get { return _asyncReadBufferSize; } } public byte[] AsyncReadBuffer { get { return _readBuffer; } } private object ThisLock { get { return this; } } public IPEndPoint RemoteIPEndPoint { get { // this property should only be called on the receive path if (_remoteEndpoint == null && _closeState == CloseState.Open) { try { _remoteEndpoint = (IPEndPoint)_socket.RemoteEndPoint; } catch (SocketException socketException) { // will never be a timeout error, so TimeSpan.Zero is ok throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertReceiveException(socketException, TimeSpan.Zero, TimeSpan.Zero)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Undefined); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } return _remoteEndpoint; } } private IOTimer<SocketConnection> SendTimer { get { if (_sendTimer == null) { if (s_onSendTimeout == null) { s_onSendTimeout = new Action<object>(OnSendTimeout); } _sendTimer = new IOTimer<SocketConnection>(s_onSendTimeout, this); } return _sendTimer; } } private IOTimer<SocketConnection> ReceiveTimer { get { if (_receiveTimer == null) { if (s_onReceiveTimeout == null) { s_onReceiveTimeout = new Action<object>(OnReceiveTimeout); } _receiveTimer = new IOTimer<SocketConnection>(s_onReceiveTimeout, this); } return _receiveTimer; } } private string RemoteEndpointAddress { get { if (_remoteEndpointAddress == null) { try { if (TryGetEndpoints(out IPEndPoint local, out IPEndPoint remote)) { _remoteEndpointAddress = remote.Address + ":" + remote.Port; } else { //null indicates not initialized. _remoteEndpointAddress = string.Empty; } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } } } return _remoteEndpointAddress; } } private static void OnReceiveTimeout(object state) { SocketConnection thisPtr = (SocketConnection)state; thisPtr.Abort(SR.Format(SR.SocketAbortedReceiveTimedOut, thisPtr._asyncReceiveTimeout), TransferOperation.Read); } private static void OnSendTimeout(object state) { SocketConnection thisPtr = (SocketConnection)state; thisPtr.Abort(4, // TraceEventType.Warning SR.Format(SR.SocketAbortedSendTimedOut, thisPtr._asyncSendTimeout), TransferOperation.Write); } private static void OnReceiveCompleted(IAsyncResult result) { ((SocketConnection)result.AsyncState).OnReceive(result); } private static void OnReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e) { ((SocketConnection)e.UserToken).OnReceiveAsync(sender, e); } private static void OnSendAsyncCompleted(object sender, SocketAsyncEventArgs e) { ((SocketConnection)e.UserToken).OnSendAsync(sender, e); } public void Abort() { Abort(null, TransferOperation.Undefined); } private void Abort(string timeoutErrorString, TransferOperation transferOperation) { int traceEventType = 4; // TraceEventType.Warning; // we could be timing out a cached connection Abort(traceEventType, timeoutErrorString, transferOperation); } private void Abort(int traceEventType) { Abort(traceEventType, null, TransferOperation.Undefined); } private void Abort(int traceEventType, string timeoutErrorString, TransferOperation transferOperation) { lock (ThisLock) { if (_closeState == CloseState.Closed) { return; } _timeoutErrorString = timeoutErrorString; _timeoutErrorTransferOperation = transferOperation; _aborted = true; _closeState = CloseState.Closed; if (_asyncReadPending) { CancelReceiveTimer(); } else { DisposeReadEventArgs(); } if (_asyncWritePending) { CancelSendTimer(); } else { DisposeWriteEventArgs(); } } _socket.Close(0); } private void AbortRead() { lock (ThisLock) { if (_asyncReadPending) { if (_closeState != CloseState.Closed) { SetUserToken(_asyncReadEventArgs, null); _asyncReadPending = false; CancelReceiveTimer(); } else { DisposeReadEventArgs(); } } } } private void CancelReceiveTimer() { if (_receiveTimer != null) { _receiveTimer.Cancel(); } } private void CancelSendTimer() { _sendTimer?.Cancel(); } private void CloseAsyncAndLinger() { _readFinTimeout = _closeTimeoutHelper.RemainingTime(); try { // A FIN (shutdown) packet has already been sent to the remote host and we're waiting for the remote // host to send a FIN back. A pending read on a socket will complete returning zero bytes when a FIN // packet is received. if (BeginReadCore(0, 1, _readFinTimeout, s_onWaitForFinComplete, this) == AsyncCompletionResult.Queued) { return; } int bytesRead = EndRead(); if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, _socket.RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, _socket.RemoteEndPoint, _readFinTimeout), timeoutException)); } ContinueClose(_closeTimeoutHelper.RemainingTime()); } private static void OnWaitForFinComplete(object state) { SocketConnection thisPtr = (SocketConnection)state; try { int bytesRead; try { bytesRead = thisPtr.EndRead(); if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, thisPtr._socket.RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, thisPtr._socket.RemoteEndPoint, thisPtr._readFinTimeout), timeoutException)); } thisPtr.ContinueClose(thisPtr._closeTimeoutHelper.RemainingTime()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } // The user has no opportunity to clean up the connection in the async and linger // code path, ensure cleanup finishes. thisPtr.Abort(); } } public void Close(TimeSpan timeout, bool asyncAndLinger) { lock (ThisLock) { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { // already closing or closed, so just return return; } _closeState = CloseState.Closing; } // first we shutdown our send-side _closeTimeoutHelper = new TimeoutHelper(timeout); Shutdown(_closeTimeoutHelper.RemainingTime()); if (asyncAndLinger) { CloseAsyncAndLinger(); } else { CloseSync(); } } private void CloseSync() { byte[] dummy = new byte[1]; // then we check for a FIN from the other side (i.e. read zero) int bytesRead; _readFinTimeout = _closeTimeoutHelper.RemainingTime(); try { bytesRead = ReadCore(dummy, 0, 1, _readFinTimeout, true); if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, _socket.RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, _socket.RemoteEndPoint, _readFinTimeout), timeoutException)); } // finally we call Close with whatever time is remaining ContinueClose(_closeTimeoutHelper.RemainingTime()); } public void ContinueClose(TimeSpan timeout) { _socket.Close(TimeoutHelper.ToMilliseconds(timeout)); lock (ThisLock) { // Abort could have been called on a separate thread and cleaned up // our buffers/completion here if (_closeState != CloseState.Closed) { if (!_asyncReadPending) { DisposeReadEventArgs(); } if (!_asyncWritePending) { DisposeWriteEventArgs(); } } _closeState = CloseState.Closed; } } public void Shutdown(TimeSpan timeout) { lock (ThisLock) { if (_isShutdown) { return; } _isShutdown = true; } try { _socket.Shutdown(SocketShutdown.Send); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, TimeSpan.MaxValue, _socketSyncSendTimeout)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Undefined); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } private void ThrowIfNotOpen() { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } private void ThrowIfClosed() { if (_closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } private bool TryGetEndpoints(out IPEndPoint localIPEndpoint, out IPEndPoint remoteIPEndpoint) { localIPEndpoint = null; remoteIPEndpoint = null; if (_closeState == CloseState.Open) { try { remoteIPEndpoint = _remoteEndpoint ?? (IPEndPoint)_socket.RemoteEndPoint; localIPEndpoint = (IPEndPoint)_socket.LocalEndPoint; } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } } } return localIPEndpoint != null && remoteIPEndpoint != null; } public object GetCoreTransport() { return _socket; } public IAsyncResult BeginValidate(Uri uri, AsyncCallback callback, object state) { return new CompletedAsyncResult<bool>(true, callback, state); } public bool EndValidate(IAsyncResult result) { return CompletedAsyncResult<bool>.End(result); } private Exception ConvertSendException(SocketException socketException, TimeSpan remainingTime, TimeSpan timeout) { return ConvertTransferException(socketException, timeout, socketException, TransferOperation.Write, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } private Exception ConvertReceiveException(SocketException socketException, TimeSpan remainingTime, TimeSpan timeout) { return ConvertTransferException(socketException, timeout, socketException, TransferOperation.Read, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } internal static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException) { return ConvertTransferException(socketException, timeout, originalException, TransferOperation.Undefined, false, null, TransferOperation.Undefined, null, TimeSpan.MaxValue); } private Exception ConvertObjectDisposedException(ObjectDisposedException originalException, TransferOperation transferOperation) { if (_timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, _timeoutErrorString, _timeoutErrorTransferOperation); } else if (_aborted) { return new CommunicationObjectAbortedException(SR.SocketConnectionDisposed, originalException); } else { return originalException; } } private static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException, TransferOperation transferOperation, bool aborted, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation, SocketConnection socketConnection, TimeSpan remainingTime) { if (socketException.ErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if (timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, timeoutErrorString, timeoutErrorTransferOperation); } // 10053 can occur due to our timeout sockopt firing, so map to TimeoutException in that case if (socketException.ErrorCode == UnsafeNativeMethods.WSAECONNABORTED && remainingTime <= TimeSpan.Zero) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } if (socketException.ErrorCode == UnsafeNativeMethods.WSAENETRESET || socketException.ErrorCode == UnsafeNativeMethods.WSAECONNABORTED || socketException.ErrorCode == UnsafeNativeMethods.WSAECONNRESET) { if (aborted) { return new CommunicationObjectAbortedException(SR.TcpLocalConnectionAborted, originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpConnectionResetError, timeout), originalException); return communicationException; } } else if (socketException.ErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } else { if (aborted) { return new CommunicationObjectAbortedException(SR.Format(SR.TcpTransferError, socketException.ErrorCode, socketException.Message), originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpTransferError, socketException.ErrorCode, socketException.Message), originalException); return communicationException; } } } private static Exception ConvertTimeoutErrorException(Exception originalException, TransferOperation transferOperation, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation) { if (timeoutErrorString == null) { Fx.Assert("Argument timeoutErrorString must not be null."); } if (transferOperation == timeoutErrorTransferOperation) { return new TimeoutException(timeoutErrorString, originalException); } else { return new CommunicationException(timeoutErrorString, originalException); } } public AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); bool abortWrite = true; try { if (WcfEventSource.Instance.SocketAsyncWriteStartIsEnabled()) { TraceWriteStart(size, true); } lock (ThisLock) { Fx.Assert(!_asyncWritePending, "Called BeginWrite twice."); ThrowIfClosed(); EnsureWriteEventArgs(); SetImmediate(immediate); SetWriteTimeout(timeout, false); SetUserToken(_asyncWriteEventArgs, this); _asyncWritePending = true; _asyncWriteCallback = callback; _asyncWriteState = state; } _asyncWriteEventArgs.SetBuffer(buffer, offset, size); if (_socket.SendAsync(_asyncWriteEventArgs)) { abortWrite = false; return AsyncCompletionResult.Queued; } HandleSendAsyncCompleted(); abortWrite = false; return AsyncCompletionResult.Completed; } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, TimeSpan.MaxValue, _asyncSendTimeout)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } finally { if (abortWrite) { AbortWrite(); } } } public void EndWrite() { if (_asyncWriteException != null) { AbortWrite(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_asyncWriteException); } lock (ThisLock) { if (!_asyncWritePending) { throw Fx.AssertAndThrow("SocketConnection.EndWrite called with no write pending."); } SetUserToken(_asyncWriteEventArgs, null); _asyncWritePending = false; if (_closeState == CloseState.Closed) { DisposeWriteEventArgs(); } } } private void OnSendAsync(object sender, SocketAsyncEventArgs eventArgs) { Fx.Assert(eventArgs != null, "Argument 'eventArgs' cannot be NULL."); CancelSendTimer(); try { HandleSendAsyncCompleted(); Fx.Assert(eventArgs.BytesTransferred == _asyncWriteEventArgs.Count, "The socket SendAsync did not send all the bytes."); } catch (SocketException socketException) { _asyncWriteException = ConvertSendException(socketException, TimeSpan.MaxValue, _asyncSendTimeout); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _asyncWriteException = exception; } FinishWrite(); } private void HandleSendAsyncCompleted() { if (_asyncWriteEventArgs.SocketError == SocketError.Success) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException((int)_asyncWriteEventArgs.SocketError)); } // This method should be called inside ThisLock private void DisposeWriteEventArgs() { if (_asyncWriteEventArgs != null) { _asyncWriteEventArgs.Completed -= s_onSocketSendCompleted; _asyncWriteEventArgs.Dispose(); } } private void AbortWrite() { lock (ThisLock) { if (_asyncWritePending) { if (_closeState != CloseState.Closed) { SetUserToken(_asyncWriteEventArgs, null); _asyncWritePending = false; CancelSendTimer(); } else { DisposeWriteEventArgs(); } } } } private void FinishWrite() { Action<object> asyncWriteCallback = _asyncWriteCallback; object asyncWriteState = _asyncWriteState; _asyncWriteState = null; _asyncWriteCallback = null; asyncWriteCallback(asyncWriteState); } public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { // as per http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b201213 // we shouldn't write more than 64K synchronously to a socket const int maxSocketWrite = 64 * 1024; ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); try { SetImmediate(immediate); int bytesToWrite = size; while (bytesToWrite > 0) { SetWriteTimeout(timeoutHelper.RemainingTime(), true); size = Math.Min(bytesToWrite, maxSocketWrite); _socket.Send(buffer, offset, size, SocketFlags.None); bytesToWrite -= size; offset += size; timeout = timeoutHelper.RemainingTime(); } } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, timeoutHelper.RemainingTime(), _socketSyncSendTimeout)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } private void TraceWriteStart(int size, bool async) { if (!async) { WcfEventSource.Instance.SocketWriteStart(_socket.GetHashCode(), size, RemoteEndpointAddress); } else { WcfEventSource.Instance.SocketAsyncWriteStart(_socket.GetHashCode(), size, RemoteEndpointAddress); } } public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { try { Write(buffer, offset, size, immediate, timeout); } finally { bufferManager.ReturnBuffer(buffer); } } public int Read(byte[] buffer, int offset, int size, TimeSpan timeout) { ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); ThrowIfNotOpen(); return ReadCore(buffer, offset, size, timeout, false); } private int ReadCore(byte[] buffer, int offset, int size, TimeSpan timeout, bool closing) { int bytesRead = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); try { SetReadTimeout(timeoutHelper.RemainingTime(), true, closing); bytesRead = _socket.Receive(buffer, offset, size, SocketFlags.None); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertReceiveException(socketException, timeoutHelper.RemainingTime(), _socketSyncReceiveTimeout)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } return bytesRead; } private void TraceSocketReadStop(int bytesRead, bool async) { if (!async) { WcfEventSource.Instance.SocketReadStop((_socket != null) ? _socket.GetHashCode() : -1, bytesRead, RemoteEndpointAddress); } else { WcfEventSource.Instance.SocketAsyncReadStop((_socket != null) ? _socket.GetHashCode() : -1, bytesRead, RemoteEndpointAddress); } } public virtual AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size); ThrowIfNotOpen(); return BeginReadCore(offset, size, timeout, callback, state); } private AsyncCompletionResult BeginReadCore(int offset, int size, TimeSpan timeout, Action<object> callback, object state) { bool abortRead = true; lock (ThisLock) { ThrowIfClosed(); EnsureReadEventArgs(); _asyncReadState = state; _asyncReadCallback = callback; SetUserToken(_asyncReadEventArgs, this); _asyncReadPending = true; SetReadTimeout(timeout, false, false); } try { if (_socket.UseOnlyOverlappedIO) { // ReceiveAsync does not respect UseOnlyOverlappedIO but BeginReceive does. IAsyncResult result = _socket.BeginReceive(AsyncReadBuffer, offset, size, SocketFlags.None, s_onReceiveCompleted, this); if (!result.CompletedSynchronously) { abortRead = false; return AsyncCompletionResult.Queued; } _asyncReadSize = _socket.EndReceive(result); } else { if (offset != _asyncReadEventArgs.Offset || size != _asyncReadEventArgs.Count) { _asyncReadEventArgs.SetBuffer(offset, size); } if (ReceiveAsync()) { abortRead = false; return AsyncCompletionResult.Queued; } HandleReceiveAsyncCompleted(); _asyncReadSize = _asyncReadEventArgs.BytesTransferred; } if (WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } abortRead = false; return AsyncCompletionResult.Completed; } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertReceiveException(socketException, TimeSpan.MaxValue, _asyncReceiveTimeout)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } finally { if (abortRead) { AbortRead(); } } } private bool ReceiveAsync() { return _socket.ReceiveAsync(_asyncReadEventArgs); } private void OnReceive(IAsyncResult result) { CancelReceiveTimer(); if (result.CompletedSynchronously) { return; } try { _asyncReadSize = _socket.EndReceive(result); if (WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } } catch (SocketException socketException) { _asyncReadException = ConvertReceiveException(socketException, TimeSpan.MaxValue, _asyncReceiveTimeout); } catch (ObjectDisposedException objectDisposedException) { _asyncReadException = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _asyncReadException = exception; } FinishRead(); } private void OnReceiveAsync(object sender, SocketAsyncEventArgs eventArgs) { Fx.Assert(eventArgs != null, "Argument 'eventArgs' cannot be NULL."); CancelReceiveTimer(); try { HandleReceiveAsyncCompleted(); _asyncReadSize = eventArgs.BytesTransferred; if (WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } } catch (SocketException socketException) { _asyncReadException = ConvertReceiveException(socketException, TimeSpan.MaxValue, _asyncReceiveTimeout); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _asyncReadException = exception; } FinishRead(); } private void HandleReceiveAsyncCompleted() { if (_asyncReadEventArgs.SocketError == SocketError.Success) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException((int)_asyncReadEventArgs.SocketError)); } private void FinishRead() { Action<object> asyncReadCallback = _asyncReadCallback; object asyncReadState = _asyncReadState; _asyncReadState = null; _asyncReadCallback = null; asyncReadCallback(asyncReadState); } // Both BeginRead/ReadAsync paths completed themselves. EndRead's only job is to deliver the result. public int EndRead() { if (_asyncReadException != null) { AbortRead(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_asyncReadException); } lock (ThisLock) { if (!_asyncReadPending) { throw Fx.AssertAndThrow("SocketConnection.EndRead called with no read pending."); } SetUserToken(_asyncReadEventArgs, null); _asyncReadPending = false; if (_closeState == CloseState.Closed) { DisposeReadEventArgs(); } } return _asyncReadSize; } // This method should be called inside ThisLock private void DisposeReadEventArgs() { if (_asyncReadEventArgs != null) { _asyncReadEventArgs.Completed -= s_onReceiveAsyncCompleted; _asyncReadEventArgs.Dispose(); } // We release the buffer only if there is no outstanding I/O TryReturnReadBuffer(); } private void TryReturnReadBuffer() { // The buffer must not be returned and nulled when an abort occurs. Since the buffer // is also accessed by higher layers, code that has not yet realized the stack is // aborted may be attempting to read from the buffer. if (_readBuffer != null && !_aborted) { _connectionBufferPool.Return(_readBuffer); _readBuffer = null; } } private void SetUserToken(SocketAsyncEventArgs args, object userToken) { // The socket args can be pinned by the overlapped callback. Ensure SocketConnection is // only pinned when there is outstanding IO. if (args != null) { args.UserToken = userToken; } } private void SetImmediate(bool immediate) { if (immediate != _noDelay) { lock (ThisLock) { ThrowIfNotOpen(); _socket.NoDelay = immediate; } _noDelay = immediate; } } private void SetReadTimeout(TimeSpan timeout, bool synchronous, bool closing) { if (synchronous) { CancelReceiveTimer(); // 0 == infinite for winsock timeouts, so we should preempt and throw if (timeout <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout))); } if (ShouldUpdateTimeout(_socketSyncReceiveTimeout, timeout)) { lock (ThisLock) { if (!closing || _closeState != CloseState.Closing) { ThrowIfNotOpen(); } _socket.ReceiveTimeout = TimeoutHelper.ToMilliseconds(timeout); } _socketSyncReceiveTimeout = timeout; } } else { _asyncReceiveTimeout = timeout; if (timeout == TimeSpan.MaxValue) { CancelReceiveTimer(); } else { ReceiveTimer.ScheduleAfter(timeout); } } } private void SetWriteTimeout(TimeSpan timeout, bool synchronous) { if (synchronous) { CancelSendTimer(); // 0 == infinite for winsock timeouts, so we should preempt and throw if (timeout <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout))); } if (ShouldUpdateTimeout(_socketSyncSendTimeout, timeout)) { lock (ThisLock) { ThrowIfNotOpen(); _socket.SendTimeout = TimeoutHelper.ToMilliseconds(timeout); } _socketSyncSendTimeout = timeout; } } else { _asyncSendTimeout = timeout; if (timeout == TimeSpan.MaxValue) { CancelSendTimer(); } else { SendTimer.ScheduleAfter(timeout); } } } private bool ShouldUpdateTimeout(TimeSpan oldTimeout, TimeSpan newTimeout) { if (oldTimeout == newTimeout) { return false; } long threshold = oldTimeout.Ticks / 10; long delta = Math.Max(oldTimeout.Ticks, newTimeout.Ticks) - Math.Min(oldTimeout.Ticks, newTimeout.Ticks); return delta > threshold; } // This method should be called inside ThisLock private void EnsureReadEventArgs() { if (_asyncReadEventArgs == null) { // Init ReadAsync state if (s_onReceiveAsyncCompleted == null) { s_onReceiveAsyncCompleted = new EventHandler<SocketAsyncEventArgs>(OnReceiveAsyncCompleted); } _asyncReadEventArgs = new SocketAsyncEventArgs(); _asyncReadEventArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length); _asyncReadEventArgs.Completed += s_onReceiveAsyncCompleted; } } // This method should be called inside ThisLock private void EnsureWriteEventArgs() { if (_asyncWriteEventArgs == null) { // Init SendAsync state if (s_onSocketSendCompleted == null) { s_onSocketSendCompleted = new EventHandler<SocketAsyncEventArgs>(OnSendAsyncCompleted); } _asyncWriteEventArgs = new SocketAsyncEventArgs(); _asyncWriteEventArgs.Completed += s_onSocketSendCompleted; } } private enum CloseState { Open, Closing, Closed, } private enum TransferOperation { Write, Read, Undefined, } } internal class SocketConnectionInitiator : IConnectionInitiator { private int _bufferSize; private ConnectionBufferPool _connectionBufferPool; public SocketConnectionInitiator(int bufferSize) { _bufferSize = bufferSize; _connectionBufferPool = new ConnectionBufferPool(bufferSize); } private IConnection CreateConnection(IPAddress address, int port) { Socket socket = null; try { AddressFamily addressFamily = address.AddressFamily; socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(address, port)); return new SocketConnection(socket, _connectionBufferPool, false); } catch { socket.Dispose(); throw; } } private async Task<IConnection> CreateConnectionAsync(IPAddress address, int port) { Socket socket = null; try { AddressFamily addressFamily = address.AddressFamily; socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(new IPEndPoint(address, port)); return new SocketConnection(socket, _connectionBufferPool, false); } catch { socket.Dispose(); throw; } } public static Exception ConvertConnectException(SocketException socketException, Uri remoteUri, TimeSpan timeSpent, Exception innerException) { if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEADDRNOTAVAIL || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNREFUSED || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { if (timeSpent == TimeSpan.MaxValue) { return new EndpointNotFoundException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new EndpointNotFoundException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENOBUFS) { return new OutOfMemoryException(SR.TcpConnectNoBufs, innerException); } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NO_SYSTEM_RESOURCES || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_OUTOFMEMORY) { return new OutOfMemoryException(SR.InsufficentMemory, socketException); } else { if (timeSpent == TimeSpan.MaxValue) { return new CommunicationException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new CommunicationException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } } private static async Task<IPAddress[]> GetIPAddressesAsync(Uri uri) { if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) { IPAddress ipAddress = IPAddress.Parse(uri.DnsSafeHost); return new IPAddress[] { ipAddress }; } IPAddress[] addresses = null; try { addresses = await DnsCache.ResolveAsync(uri); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host), socketException)); } if (addresses.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host))); } return addresses; } private static TimeoutException CreateTimeoutException(Uri uri, TimeSpan timeout, IPAddress[] addresses, int invalidAddressCount, SocketException innerException) { StringBuilder addressStringBuilder = new StringBuilder(); for (int i = 0; i < invalidAddressCount; i++) { if (addresses[i] == null) { continue; } if (addressStringBuilder.Length > 0) { addressStringBuilder.Append(", "); } addressStringBuilder.Append(addresses[i].ToString()); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.TcpConnectingToViaTimedOut, uri.AbsoluteUri, timeout.ToString(), invalidAddressCount, addresses.Length, addressStringBuilder.ToString()), innerException)); } public IConnection Connect(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = SocketConnectionInitiator.GetIPAddressesAsync(uri).GetAwaiter().GetResult(); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = CreateConnection(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } public async Task<IConnection> ConnectAsync(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = await SocketConnectionInitiator.GetIPAddressesAsync(uri); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = await CreateConnectionAsync(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } } }
using System; using System.Collections.Generic; using System.Linq; namespace SqlKata { public abstract class AbstractQuery { public AbstractQuery Parent; } public abstract partial class BaseQuery<Q> : AbstractQuery where Q : BaseQuery<Q> { public List<AbstractClause> Clauses { get; set; } = new List<AbstractClause>(); private bool orFlag = false; private bool notFlag = false; public string EngineScope = null; public Q SetEngineScope(string engine) { this.EngineScope = engine; return (Q)this; } public BaseQuery() { } /// <summary> /// Return a cloned copy of the current query. /// </summary> /// <returns></returns> public virtual Q Clone() { var q = NewQuery(); q.Clauses = this.Clauses.Select(x => x.Clone()).ToList(); return q; } public Q SetParent(AbstractQuery parent) { if (this == parent) { throw new ArgumentException($"Cannot set the same {nameof(AbstractQuery)} as a parent of itself"); } this.Parent = parent; return (Q)this; } public abstract Q NewQuery(); public Q NewChild() { var newQuery = NewQuery().SetParent((Q)this); newQuery.EngineScope = this.EngineScope; return newQuery; } /// <summary> /// Add a component clause to the query. /// </summary> /// <param name="component"></param> /// <param name="clause"></param> /// <param name="engineCode"></param> /// <returns></returns> public Q AddComponent(string component, AbstractClause clause, string engineCode = null) { if (engineCode == null) { engineCode = EngineScope; } clause.Engine = engineCode; clause.Component = component; Clauses.Add(clause); return (Q)this; } /// <summary> /// If the query already contains a clause for the given component /// and engine, replace it with the specified clause. Otherwise, just /// add the clause. /// </summary> /// <param name="component"></param> /// <param name="clause"></param> /// <param name="engineCode"></param> /// <returns></returns> public Q AddOrReplaceComponent(string component, AbstractClause clause, string engineCode = null) { engineCode = engineCode ?? EngineScope; var current = GetComponents(component).SingleOrDefault(c => c.Engine == engineCode); if (current != null) Clauses.Remove(current); return AddComponent(component, clause, engineCode); } /// <summary> /// Get the list of clauses for a component. /// </summary> /// <returns></returns> public List<C> GetComponents<C>(string component, string engineCode = null) where C : AbstractClause { if (engineCode == null) { engineCode = EngineScope; } var clauses = Clauses .Where(x => x.Component == component) .Where(x => engineCode == null || x.Engine == null || engineCode == x.Engine) .Cast<C>(); return clauses.ToList(); } /// <summary> /// Get the list of clauses for a component. /// </summary> /// <param name="component"></param> /// <param name="engineCode"></param> /// <returns></returns> public List<AbstractClause> GetComponents(string component, string engineCode = null) { if (engineCode == null) { engineCode = EngineScope; } return GetComponents<AbstractClause>(component, engineCode); } /// <summary> /// Get a single component clause from the query. /// </summary> /// <returns></returns> public C GetOneComponent<C>(string component, string engineCode = null) where C : AbstractClause { engineCode = engineCode ?? EngineScope; var all = GetComponents<C>(component, engineCode); return all.FirstOrDefault(c => c.Engine == engineCode) ?? all.FirstOrDefault(c => c.Engine == null); } /// <summary> /// Get a single component clause from the query. /// </summary> /// <param name="component"></param> /// <param name="engineCode"></param> /// <returns></returns> public AbstractClause GetOneComponent(string component, string engineCode = null) { if (engineCode == null) { engineCode = EngineScope; } return GetOneComponent<AbstractClause>(component, engineCode); } /// <summary> /// Return whether the query has clauses for a component. /// </summary> /// <param name="component"></param> /// <param name="engineCode"></param> /// <returns></returns> public bool HasComponent(string component, string engineCode = null) { if (engineCode == null) { engineCode = EngineScope; } return GetComponents(component, engineCode).Any(); } /// <summary> /// Remove all clauses for a component. /// </summary> /// <param name="component"></param> /// <param name="engineCode"></param> /// <returns></returns> public Q ClearComponent(string component, string engineCode = null) { if (engineCode == null) { engineCode = EngineScope; } Clauses = Clauses .Where(x => !(x.Component == component && (engineCode == null || x.Engine == null || engineCode == x.Engine))) .ToList(); return (Q)this; } /// <summary> /// Set the next boolean operator to "and" for the "where" clause. /// </summary> /// <returns></returns> protected Q And() { orFlag = false; return (Q)this; } /// <summary> /// Set the next boolean operator to "or" for the "where" clause. /// </summary> /// <returns></returns> public Q Or() { orFlag = true; return (Q)this; } /// <summary> /// Set the next "not" operator for the "where" clause. /// </summary> /// <returns></returns> public Q Not(bool flag = true) { notFlag = flag; return (Q)this; } /// <summary> /// Get the boolean operator and reset it to "and" /// </summary> /// <returns></returns> protected bool GetOr() { var ret = orFlag; // reset the flag orFlag = false; return ret; } /// <summary> /// Get the "not" operator and clear it /// </summary> /// <returns></returns> protected bool GetNot() { var ret = notFlag; // reset the flag notFlag = false; return ret; } /// <summary> /// Add a from Clause /// </summary> /// <param name="table"></param> /// <returns></returns> public Q From(string table) { return AddOrReplaceComponent("from", new FromClause { Table = table, }); } public Q From(Query query, string alias = null) { query = query.Clone(); query.SetParent((Q)this); if (alias != null) { query.As(alias); }; return AddOrReplaceComponent("from", new QueryFromClause { Query = query }); } public Q FromRaw(string sql, params object[] bindings) { return AddOrReplaceComponent("from", new RawFromClause { Expression = sql, Bindings = bindings, }); } public Q From(Func<Query, Query> callback, string alias = null) { var query = new Query(); query.SetParent((Q)this); return From(callback.Invoke(query), alias); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Web; using Umbraco.Core.Logging; namespace Umbraco.Core.ObjectResolution { /// <summary> /// The base class for all many-objects resolvers. /// </summary> /// <typeparam name="TResolver">The type of the concrete resolver class.</typeparam> /// <typeparam name="TResolved">The type of the resolved objects.</typeparam> public abstract class ManyObjectsResolverBase<TResolver, TResolved> : ResolverBase<TResolver> where TResolved : class where TResolver : ResolverBase { private Lazy<IEnumerable<TResolved>> _applicationInstances; private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(); private readonly string _httpContextKey; private readonly List<Type> _instanceTypes = new List<Type>(); private IEnumerable<TResolved> _sortedValues; private int _defaultPluginWeight = 10; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// and an optional lifetime scope. /// </summary> /// <param name="serviceProvider"></param> /// <param name="logger"></param> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); if (logger == null) throw new ArgumentNullException("logger"); CanResolveBeforeFrozen = false; if (scope == ObjectLifetimeScope.HttpRequest) { if (HttpContext.Current == null) throw new InvalidOperationException("Use alternative constructor accepting a HttpContextBase object in order to set the lifetime scope to HttpRequest when HttpContext.Current is null"); CurrentHttpContext = new HttpContextWrapper(HttpContext.Current); } ServiceProvider = serviceProvider; Logger = logger; LifetimeScope = scope; if (scope == ObjectLifetimeScope.HttpRequest) _httpContextKey = GetType().FullName; _instanceTypes = new List<Type>(); InitializeAppInstances(); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use ctor specifying IServiceProvider instead")] protected ManyObjectsResolverBase(ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, scope) { } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an empty list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="serviceProvider"></param> /// <param name="logger"></param> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> protected ManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, HttpContextBase httpContext) { if (serviceProvider == null) throw new ArgumentNullException("serviceProvider"); if (httpContext == null) throw new ArgumentNullException("httpContext"); CanResolveBeforeFrozen = false; Logger = logger; LifetimeScope = ObjectLifetimeScope.HttpRequest; _httpContextKey = GetType().FullName; ServiceProvider = serviceProvider; CurrentHttpContext = httpContext; _instanceTypes = new List<Type>(); InitializeAppInstances(); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use ctor specifying IServiceProvider instead")] protected ManyObjectsResolverBase(HttpContextBase httpContext) : this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext) { } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of object types, /// and an optional lifetime scope. /// </summary> /// <param name="serviceProvider"></param> /// <param name="logger"></param> /// <param name="value">The list of object types.</param> /// <param name="scope">The lifetime scope of instantiated objects, default is per Application.</param> /// <remarks>If <paramref name="scope"/> is per HttpRequest then there must be a current HttpContext.</remarks> /// <exception cref="InvalidOperationException"><paramref name="scope"/> is per HttpRequest but the current HttpContext is null.</exception> protected ManyObjectsResolverBase(IServiceProvider serviceProvider, ILogger logger, IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(serviceProvider, logger, scope) { _instanceTypes = value.ToList(); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use ctor specifying IServiceProvider instead")] protected ManyObjectsResolverBase(IEnumerable<Type> value, ObjectLifetimeScope scope = ObjectLifetimeScope.Application) : this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, value, scope) { } /// <summary> /// Initializes a new instance of the <see cref="ManyObjectsResolverBase{TResolver, TResolved}"/> class with an initial list of objects, /// with creation of objects based on an HttpRequest lifetime scope. /// </summary> /// <param name="httpContext">The HttpContextBase corresponding to the HttpRequest.</param> /// <param name="value">The list of object types.</param> /// <exception cref="ArgumentNullException"><paramref name="httpContext"/> is <c>null</c>.</exception> [Obsolete("Use ctor specifying IServiceProvider instead")] protected ManyObjectsResolverBase(HttpContextBase httpContext, IEnumerable<Type> value) : this(new ActivatorServiceProvider(), LoggerResolver.Current.Logger, httpContext) { _instanceTypes = value.ToList(); } #endregion private void InitializeAppInstances() { _applicationInstances = new Lazy<IEnumerable<TResolved>>(() => CreateInstances().ToArray()); } /// <summary> /// Gets or sets a value indicating whether the resolver can resolve objects before resolution is frozen. /// </summary> /// <remarks>This is false by default and is used for some special internal resolvers.</remarks> internal bool CanResolveBeforeFrozen { get; set; } /// <summary> /// Gets the list of types to create instances from. /// </summary> protected virtual IEnumerable<Type> InstanceTypes { get { return _instanceTypes; } } /// <summary> /// Gets or sets the <see cref="HttpContextBase"/> used to initialize this object, if any. /// </summary> /// <remarks>If not null, then <c>LifetimeScope</c> will be <c>ObjectLifetimeScope.HttpRequest</c>.</remarks> protected HttpContextBase CurrentHttpContext { get; private set; } /// <summary> /// Returns the service provider used to instantiate objects /// </summary> public IServiceProvider ServiceProvider { get; private set; } public ILogger Logger { get; private set; } /// <summary> /// Gets or sets the lifetime scope of resolved objects. /// </summary> protected ObjectLifetimeScope LifetimeScope { get; private set; } /// <summary> /// Gets the resolved object instances, sorted by weight. /// </summary> /// <returns>The sorted resolved object instances.</returns> /// <remarks> /// <para>The order is based upon the <c>WeightedPluginAttribute</c> and <c>DefaultPluginWeight</c>.</para> /// <para>Weights are sorted ascendingly (lowest weights come first).</para> /// </remarks> protected IEnumerable<TResolved> GetSortedValues() { if (_sortedValues == null) { var values = Values.ToList(); values.Sort((f1, f2) => GetObjectWeight(f1).CompareTo(GetObjectWeight(f2))); _sortedValues = values; } return _sortedValues; } /// <summary> /// Gets or sets the default type weight. /// </summary> /// <remarks>Determines the weight of types that do not have a <c>WeightedPluginAttribute</c> set on /// them, when calling <c>GetSortedValues</c>.</remarks> protected virtual int DefaultPluginWeight { get { return _defaultPluginWeight; } set { _defaultPluginWeight = value; } } /// <summary> /// Returns the weight of an object for user with GetSortedValues /// </summary> /// <param name="o"></param> /// <returns></returns> protected virtual int GetObjectWeight(object o) { var type = o.GetType(); var attr = type.GetCustomAttribute<WeightedPluginAttribute>(true); return attr == null ? DefaultPluginWeight : attr.Weight; } /// <summary> /// Gets the resolved object instances. /// </summary> /// <exception cref="InvalidOperationException"><c>CanResolveBeforeFrozen</c> is false, and resolution is not frozen.</exception> protected IEnumerable<TResolved> Values { get { using (Resolution.Reader(CanResolveBeforeFrozen)) { // note: we apply .ToArray() to the output of CreateInstance() because that is an IEnumerable that // comes from the PluginManager we want to be _sure_ that it's not a Linq of some sort, but the // instances have actually been instanciated when we return. switch (LifetimeScope) { case ObjectLifetimeScope.HttpRequest: // create new instances per HttpContext if (CurrentHttpContext.Items[_httpContextKey] == null) { var instances = CreateInstances().ToArray(); var disposableInstances = instances.OfType<IDisposable>(); //Ensure anything resolved that is IDisposable is disposed when the request termintates foreach (var disposable in disposableInstances) { CurrentHttpContext.DisposeOnPipelineCompleted(disposable); } CurrentHttpContext.Items[_httpContextKey] = instances; } return (TResolved[])CurrentHttpContext.Items[_httpContextKey]; case ObjectLifetimeScope.Application: return _applicationInstances.Value; case ObjectLifetimeScope.Transient: default: // create new instances each time return CreateInstances().ToArray(); } } } } /// <summary> /// Creates the object instances for the types contained in the types collection. /// </summary> /// <returns>A list of objects of type <typeparamref name="TResolved"/>.</returns> protected virtual IEnumerable<TResolved> CreateInstances() { return ServiceProvider.CreateInstances<TResolved>(InstanceTypes, Logger); } #region Types collection manipulation /// <summary> /// Removes a type. /// </summary> /// <param name="value">The type to remove.</param> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public virtual void RemoveType(Type value) { EnsureSupportsRemove(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); l.UpgradeToWriteLock(); _instanceTypes.Remove(value); } } /// <summary> /// Removes a type. /// </summary> /// <typeparam name="T">The type to remove.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support removing types, or /// the type is not a valid type for the resolver.</exception> public void RemoveType<T>() where T : TResolved { RemoveType(typeof(T)); } /// <summary> /// Adds types. /// </summary> /// <param name="types">The types to add.</param> /// <remarks>The types are appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// a type is not a valid type for the resolver, or a type is already in the collection of types.</exception> protected void AddTypes(IEnumerable<Type> types) { EnsureSupportsAdd(); using (Resolution.Configuration) using (new WriteLock(_lock)) { foreach(var t in types) { EnsureCorrectType(t); if (_instanceTypes.Contains(t)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", t.FullName)); } _instanceTypes.Add(t); } } } /// <summary> /// Adds a type. /// </summary> /// <param name="value">The type to add.</param> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void AddType(Type value) { EnsureSupportsAdd(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Add(value); } } /// <summary> /// Adds a type. /// </summary> /// <typeparam name="T">The type to add.</typeparam> /// <remarks>The type is appended at the end of the list.</remarks> /// <exception cref="InvalidOperationException">the resolver does not support adding types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public void AddType<T>() where T : TResolved { AddType(typeof(T)); } /// <summary> /// Clears the list of types /// </summary> /// <exception cref="InvalidOperationException">the resolver does not support clearing types.</exception> public virtual void Clear() { EnsureSupportsClear(); using (Resolution.Configuration) using (new WriteLock(_lock)) { _instanceTypes.Clear(); } } /// <summary> /// WARNING! Do not use this unless you know what you are doing, clear all types registered and instances /// created. Typically only used if a resolver is no longer used in an application and memory is to be GC'd /// </summary> internal void ResetCollections() { using (new WriteLock(_lock)) { _instanceTypes.Clear(); _sortedValues = null; _applicationInstances = null; } } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public virtual void InsertType(int index, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(value); if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// the type is not a valid type for the resolver, or the type is already in the collection of types.</exception> public virtual void InsertType(Type value) { InsertType(0, value); } /// <summary> /// Inserts a type at the specified index. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> /// <param name="index">The zero-based index at which the type should be inserted.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is out of range.</exception> public void InsertType<T>(int index) where T : TResolved { InsertType(index, typeof(T)); } /// <summary> /// Inserts a type at the beginning of the list. /// </summary> /// <typeparam name="T">The type to insert.</typeparam> public void InsertType<T>() where T : TResolved { InsertType(0, typeof(T)); } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <param name="existingType">The existing type before which to insert.</param> /// <param name="value">The type to insert.</param> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public virtual void InsertTypeBefore(Type existingType, Type value) { EnsureSupportsInsert(); using (Resolution.Configuration) using (var l = new UpgradeableReadLock(_lock)) { EnsureCorrectType(existingType); EnsureCorrectType(value); if (_instanceTypes.Contains(existingType) == false) { throw new InvalidOperationException(string.Format( "Type {0} is not in the collection of types.", existingType.FullName)); } if (_instanceTypes.Contains(value)) { throw new InvalidOperationException(string.Format( "Type {0} is already in the collection of types.", value.FullName)); } int index = _instanceTypes.IndexOf(existingType); l.UpgradeToWriteLock(); _instanceTypes.Insert(index, value); } } /// <summary> /// Inserts a type before a specified, already existing type. /// </summary> /// <typeparam name="TExisting">The existing type before which to insert.</typeparam> /// <typeparam name="T">The type to insert.</typeparam> /// <exception cref="InvalidOperationException">the resolver does not support inserting types, or /// one of the types is not a valid type for the resolver, or the existing type is not in the collection, /// or the new type is already in the collection of types.</exception> public void InsertTypeBefore<TExisting, T>() where TExisting : TResolved where T : TResolved { InsertTypeBefore(typeof(TExisting), typeof(T)); } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <param name="value">The type to look for.</param> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public virtual bool ContainsType(Type value) { using (new ReadLock(_lock)) { return _instanceTypes.Contains(value); } } /// <summary> /// Gets the types in the collection of types. /// </summary> /// <returns>The types in the collection of types.</returns> /// <remarks>Returns an enumeration, the list cannot be modified.</remarks> public virtual IEnumerable<Type> GetTypes() { Type[] types; using (new ReadLock(_lock)) { types = _instanceTypes.ToArray(); } return types; } /// <summary> /// Returns a value indicating whether the specified type is already in the collection of types. /// </summary> /// <typeparam name="T">The type to look for.</typeparam> /// <returns>A value indicating whether the type is already in the collection of types.</returns> public bool ContainsType<T>() where T : TResolved { return ContainsType(typeof(T)); } #endregion /// <summary> /// Returns a WriteLock to use when modifying collections /// </summary> /// <returns></returns> protected WriteLock GetWriteLock() { return new WriteLock(_lock); } #region Type utilities /// <summary> /// Ensures that a type is a valid type for the resolver. /// </summary> /// <param name="value">The type to test.</param> /// <exception cref="InvalidOperationException">the type is not a valid type for the resolver.</exception> protected virtual void EnsureCorrectType(Type value) { if (TypeHelper.IsTypeAssignableFrom<TResolved>(value) == false) throw new InvalidOperationException(string.Format( "Type {0} is not an acceptable type for resolver {1}.", value.FullName, GetType().FullName)); } #endregion #region Types collection manipulation support /// <summary> /// Ensures that the resolver supports removing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support removing types.</exception> protected void EnsureSupportsRemove() { if (SupportsRemove == false) throw new InvalidOperationException("This resolver does not support removing types"); } /// <summary> /// Ensures that the resolver supports clearing types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support clearing types.</exception> protected void EnsureSupportsClear() { if (SupportsClear == false) throw new InvalidOperationException("This resolver does not support clearing types"); } /// <summary> /// Ensures that the resolver supports adding types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support adding types.</exception> protected void EnsureSupportsAdd() { if (SupportsAdd == false) throw new InvalidOperationException("This resolver does not support adding new types"); } /// <summary> /// Ensures that the resolver supports inserting types. /// </summary> /// <exception cref="InvalidOperationException">The resolver does not support inserting types.</exception> protected void EnsureSupportsInsert() { if (SupportsInsert == false) throw new InvalidOperationException("This resolver does not support inserting new types"); } /// <summary> /// Gets a value indicating whether the resolver supports adding types. /// </summary> protected virtual bool SupportsAdd { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports inserting types. /// </summary> protected virtual bool SupportsInsert { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports clearing types. /// </summary> protected virtual bool SupportsClear { get { return true; } } /// <summary> /// Gets a value indicating whether the resolver supports removing types. /// </summary> protected virtual bool SupportsRemove { get { return true; } } #endregion } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2010 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class DatabaseExceptionTest { [Test] public void TestDB_REP_DUPMASTER() { DatabaseException.ThrowException(ErrorCodes.DB_REP_DUPMASTER); } [Test] public void TestDB_REP_HOLDELECTION() { DatabaseException.ThrowException(ErrorCodes.DB_REP_HOLDELECTION); } [Test] public void TestDB_REP_IGNORE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_IGNORE); } [Test] public void TestDB_REP_ISPERM() { DatabaseException.ThrowException(ErrorCodes.DB_REP_ISPERM); } [Test] public void TestDB_REP_JOIN_FAILURE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_JOIN_FAILURE); } [Test] public void TestDB_REP_NEWSITE() { DatabaseException.ThrowException(ErrorCodes.DB_REP_NEWSITE); } [Test] public void TestDB_REP_NOTPERM() { DatabaseException.ThrowException(ErrorCodes.DB_REP_NOTPERM); } [Test] public void TestDeadlockException() { try { DatabaseException.ThrowException(ErrorCodes.DB_LOCK_DEADLOCK); } catch (DeadlockException e) { Assert.AreEqual(ErrorCodes.DB_LOCK_DEADLOCK, e.ErrorCode); } } [Test] public void TestForeignConflictException() { try { DatabaseException.ThrowException(ErrorCodes.DB_FOREIGN_CONFLICT); } catch (ForeignConflictException e) { Assert.AreEqual(ErrorCodes.DB_FOREIGN_CONFLICT, e.ErrorCode); } } [Test] public void TestKeyEmptyException() { try { DatabaseException.ThrowException(ErrorCodes.DB_KEYEMPTY); } catch (KeyEmptyException e) { Assert.AreEqual(ErrorCodes.DB_KEYEMPTY, e.ErrorCode); } } [Test] public void TestKeyExistException() { try { DatabaseException.ThrowException(ErrorCodes.DB_KEYEXIST); } catch (KeyExistException e) { Assert.AreEqual(ErrorCodes.DB_KEYEXIST, e.ErrorCode); } } [Test] public void TestLeaseExpiredException() { try { DatabaseException.ThrowException(ErrorCodes.DB_REP_LEASE_EXPIRED); } catch (LeaseExpiredException e) { Assert.AreEqual(ErrorCodes.DB_REP_LEASE_EXPIRED, e.ErrorCode); } } [Test] public void TestLockNotGrantedException() { try { DatabaseException.ThrowException(ErrorCodes.DB_LOCK_NOTGRANTED); } catch (LockNotGrantedException e) { Assert.AreEqual(ErrorCodes.DB_LOCK_NOTGRANTED, e.ErrorCode); } } [Test] public void TestNotFoundException() { try { DatabaseException.ThrowException(ErrorCodes.DB_NOTFOUND); } catch (NotFoundException e) { Assert.AreEqual(ErrorCodes.DB_NOTFOUND, e.ErrorCode); } } [Test] public void TestOldVersionException() { try { DatabaseException.ThrowException(ErrorCodes.DB_OLD_VERSION); } catch (OldVersionException e) { Assert.AreEqual(ErrorCodes.DB_OLD_VERSION, e.ErrorCode); } } [Test] public void TestPageNotFoundException() { try { DatabaseException.ThrowException(ErrorCodes.DB_PAGE_NOTFOUND); } catch (PageNotFoundException e) { Assert.AreEqual(ErrorCodes.DB_PAGE_NOTFOUND, e.ErrorCode); } } [Test] public void TestRunRecoveryException() { try { DatabaseException.ThrowException(ErrorCodes.DB_RUNRECOVERY); } catch (RunRecoveryException e) { Assert.AreEqual(ErrorCodes.DB_RUNRECOVERY, e.ErrorCode); } } [Test] public void TestVerificationException() { try { DatabaseException.ThrowException(ErrorCodes.DB_VERIFY_BAD); } catch (VerificationException e) { Assert.AreEqual(ErrorCodes.DB_VERIFY_BAD, e.ErrorCode); } } [Test] public void TestVersionMismatchException() { try { DatabaseException.ThrowException(ErrorCodes.DB_VERSION_MISMATCH); } catch (VersionMismatchException e) { Assert.AreEqual(ErrorCodes.DB_VERSION_MISMATCH, e.ErrorCode); } } } }
using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.Views.Text; using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace ReactNative.Views.TextInput { /// <summary> /// View manager for <see cref="PasswordBox"/>. /// </summary> class ReactPasswordBoxManager : BaseViewManager<PasswordBox, ReactPasswordBoxShadowNode> { internal static readonly Color DefaultPlaceholderTextColor = Color.FromArgb(255, 0, 0, 0); /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "PasswordBoxWindows"; } } /// <summary> /// The exported custom bubbling event types. /// </summary> public override IReadOnlyDictionary<string, object> ExportedCustomBubblingEventTypeConstants { get { return new Dictionary<string, object>() { { "topSubmitEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onSubmitEditing" }, { "captured" , "onSubmitEditingCapture" } } } } }, { "topEndEditing", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onEndEditing" }, { "captured" , "onEndEditingCapture" } } } } }, { "topFocus", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onFocus" }, { "captured" , "onFocusCapture" } } } } }, { "topBlur", new Dictionary<string, object>() { { "phasedRegistrationNames", new Dictionary<string, string>() { { "bubbled" , "onBlur" }, { "captured" , "onBlurCapture" } } } } }, }; } } /// <summary> /// Sets the password character on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="passwordCharString">The password masking character to set.</param> [ReactProp("passwordChar")] public void SetPasswordChar(PasswordBox view, string passwordCharString) { view.PasswordChar = passwordCharString.ToCharArray().First(); } /// <summary> /// Sets the password reveal mode on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="revealModeString">The reveal mode, either Hidden, Peek, or Visibile.</param> [ReactProp("passwordRevealMode")] public void SetPasswordRevealMode(PasswordBox view, string revealModeString) { throw new NotSupportedException("Password Reveal Mode is not supported by WPF."); } /// <summary> /// Sets the font size on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(PasswordBox view, double fontSize) { view.FontSize = fontSize; } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(PasswordBox view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="familyName">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(PasswordBox view, string familyName) { view.FontFamily = familyName != null ? new FontFamily(familyName) : new FontFamily(); } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontWeightString">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(PasswordBox view, string fontWeightString) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString); view.FontWeight = fontWeight ?? FontWeights.Normal; } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontStyleString">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(PasswordBox view, string fontStyleString) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString); view.FontStyle = fontStyle ?? new FontStyle(); } /// <summary> /// Sets the default text placeholder property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="placeholder">The placeholder text.</param> [ReactProp("placeholder")] public void SetPlaceholder(PasswordBox view, string placeholder) { PlaceholderAdorner.SetText(view, placeholder); } /// <summary> /// Sets the placeholderTextColor property on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The placeholder text color.</param> [ReactProp("placeholderTextColor", CustomType = "Color")] public void SetPlaceholderTextColor(PasswordBox view, uint? color) { var brush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultPlaceholderTextColor); PlaceholderAdorner.SetTextColor(view, brush); } /// <summary> /// Sets the border color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance</param> /// <param name="color">The masked color value.</param> [ReactProp("borderColor", CustomType = "Color")] public void SetBorderColor(PasswordBox view, uint? color) { view.BorderBrush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(ReactTextInputManager.DefaultTextBoxBorder); } /// <summary> /// Sets the background color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(PasswordBox view, uint? color) { view.Background = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(Colors.White); } /// <summary> /// Sets the selection color for the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp("selectionColor", CustomType = "Color")] public void SetSelectionColor(PasswordBox view, uint color) { view.SelectionBrush = new SolidColorBrush(ColorHelpers.Parse(color)); view.CaretBrush = new SolidColorBrush(ColorHelpers.Parse(color)); } /// <summary> /// Sets the text alignment property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlignVertical)] public void SetTextVerticalAlign(PasswordBox view, string alignment) { view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment); } /// <summary> /// Sets the editablity property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="editable">The editable flag.</param> [ReactProp("editable")] public void SetEditable(PasswordBox view, bool editable) { view.IsEnabled = editable; } /// <summary> /// Sets the max character length property on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="maxCharLength">The max length.</param> [ReactProp("maxLength")] public void SetMaxLength(PasswordBox view, int maxCharLength) { view.MaxLength = maxCharLength; } /// <summary> /// Sets the keyboard type on the <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="keyboardType">The keyboard type.</param> [ReactProp("keyboardType")] public void SetKeyboardType(PasswordBox view, string keyboardType) { var inputScope = new InputScope(); var nameValue = keyboardType != null ? InputScopeHelpers.FromStringForPasswordBox(keyboardType) : InputScopeNameValue.Password; inputScope.Names.Add(new InputScopeName(nameValue)); view.InputScope = inputScope; } /// <summary> /// Sets the border width for a <see cref="PasswordBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="width">The border width.</param> [ReactProp(ViewProps.BorderWidth)] public void SetBorderWidth(PasswordBox view, int width) { view.BorderThickness = new Thickness(width); } public override ReactPasswordBoxShadowNode CreateShadowNodeInstance() { return new ReactPasswordBoxShadowNode(); } /// <summary> /// Update the view with extra data. /// </summary> /// <param name="view">The view instance.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(PasswordBox view, object extraData) { var paddings = extraData as float[]; if (paddings != null) { view.Padding = new Thickness( paddings[0], paddings[1], paddings[2], paddings[3]); } } /// <summary> /// Returns the view instance for <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The themed React Context</param> /// <returns>A new initialized <see cref="PasswordBox"/></returns> protected override PasswordBox CreateViewInstance(ThemedReactContext reactContext) { return new PasswordBox(); } /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="PasswordBox"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public override void ReceiveCommand(PasswordBox view, int commandId, JArray args) { if (commandId == ReactTextInputManager.FocusTextInput) { view.Focus(); } else if (commandId == ReactTextInputManager.BlurTextInput) { Keyboard.ClearFocus(); } } /// <summary> /// Installing the textchanged event emitter on the <see cref="TextInput"/> Control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/> view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, PasswordBox view) { base.AddEventEmitters(reactContext, view); view.PasswordChanged += OnPasswordChanged; view.GotFocus += OnGotFocus; view.LostFocus += OnLostFocus; view.KeyDown += OnKeyDown; } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactTextInputManager"/>. /// subclass. Unregister all event handlers for the <see cref="PasswordBox"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="PasswordBox"/>.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, PasswordBox view) { base.OnDropViewInstance(reactContext, view); view.KeyDown -= OnKeyDown; view.LostFocus -= OnLostFocus; view.GotFocus -= OnGotFocus; view.PasswordChanged -= OnPasswordChanged; } /// <summary> /// Sets the dimensions of the view. /// </summary> /// <param name="view">The view.</param> /// <param name="dimensions">The output buffer.</param> public override void SetDimensions(PasswordBox view, Dimensions dimensions) { base.SetDimensions(view, dimensions); view.MinWidth = dimensions.Width; view.MinHeight = dimensions.Height; } private void OnPasswordChanged(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( textBox.GetTag(), textBox.Password, 0)); } private void OnGotFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputFocusEvent(textBox.GetTag())); } private void OnLostFocus(object sender, RoutedEventArgs e) { var textBox = (PasswordBox)sender; var eventDispatcher = textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher; eventDispatcher.DispatchEvent( new ReactTextInputBlurEvent(textBox.GetTag())); eventDispatcher.DispatchEvent( new ReactTextInputEndEditingEvent( textBox.GetTag(), textBox.Password)); } private void OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var textBox = (PasswordBox)sender; e.Handled = true; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputSubmitEditingEvent( textBox.GetTag(), textBox.Password)); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml; using Orleans.MultiCluster; using Orleans.Runtime.Configuration; using Orleans.Runtime.MembershipService; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private Logger logger; private IMembershipTable membershipTable; public override Task OnActivateAsync() { logger = LogManager.GetLogger("ManagementGrain", LoggerType.Runtime); return TaskDone.Done; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); var t = onlyActive ? table.Members.Where(item => item.Item1.Status == SiloStatus.Active).ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status) : table.Members.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); return t; } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task SetSystemLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetSystemTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetSystemLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetAppLogLevel(SiloAddress[] siloAddresses, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetAppTraceLevel={1} {0}", Utils.EnumerableToString(silos), traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetAppLogLevel(traceLevel)); return Task.WhenAll(actionPromises); } public Task SetLogLevel(SiloAddress[] siloAddresses, string logName, int traceLevel) { var silos = GetSiloAddresses(siloAddresses); logger.Info("SetLogLevel[{1}]={2} {0}", Utils.EnumerableToString(silos), logName, traceLevel); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).SetLogLevel(logName, traceLevel)); return Task.WhenAll(actionPromises); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsVerbose) logger.Verbose("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing) { var global = new[] { "Globals/", "/Globals/", "OrleansConfiguration/Globals/", "/OrleansConfiguration/Globals/" }; if (hostIds != null && configuration.Keys.Any(k => global.Any(k.StartsWith))) throw new ArgumentException("Must update global configuration settings on all silos"); var silos = GetSiloAddresses(hostIds); if (silos.Length == 0) return; var document = XPathValuesToXml(configuration); if (tracing != null) { AddXPathValue(document, new[] { "OrleansConfiguration", "Defaults", "Tracing" }, null); var parent = document["OrleansConfiguration"]["Defaults"]["Tracing"]; foreach (var trace in tracing) { var child = document.CreateElement("TraceLevelOverride"); child.SetAttribute("LogPrefix", trace.Key); child.SetAttribute("TraceLevel", trace.Value); parent.AppendChild(child); } } using(var sw = new StringWriter()) { using(var xw = XmlWriter.Create(sw)) { document.WriteTo(xw); xw.Flush(); var xml = sw.ToString(); // do first one, then all the rest to avoid spamming all the silos in case of a parameter error await GetSiloControlReference(silos[0]).UpdateConfiguration(xml); await Task.WhenAll(silos.Skip(1).Select(s => GetSiloControlReference(s).UpdateConfiguration(xml))); } } } public async Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations) { SiloAddress[] silos = GetSiloAddresses(hostIds); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).UpdateStreamProviders(streamProviderConfigurations)); await Task.WhenAll(actionPromises); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsVerbose) { logger.Verbose("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private async Task<IMembershipTable> GetMembershipTable() { if (membershipTable == null) { var factory = new MembershipFactory((IInternalGrainFactory)this.GrainFactory); membershipTable = factory.GetMembershipTable(Silo.CurrentSilo.GlobalConfig); await membershipTable.InitializeMembershipTable(Silo.CurrentSilo.GlobalConfig, false, LogManager.GetLogger(membershipTable.GetType().Name)); } return membershipTable; } private static SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return InsideRuntimeClient.Current.Catalog.SiloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action functiona to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } #region MultiCluster private MultiClusterNetwork.IMultiClusterOracle GetMultiClusterOracle() { if (!Silo.CurrentSilo.GlobalConfig.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return Silo.CurrentSilo.LocalMultiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_vec4 swizzle(vec4 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static float[] Values(vec4 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<float> GetEnumerator(vec4 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(vec4 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(vec4 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(vec4 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(vec4 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(vec4 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (4). /// </summary> public static int Count(vec4 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(vec4 v, vec4 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(vec4 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(vec4 v) => v.GetHashCode(); /// <summary> /// Returns true iff distance between lhs and rhs is less than or equal to epsilon /// </summary> public static bool ApproxEqual(vec4 lhs, vec4 rhs, float eps = 0.1f) => vec4.ApproxEqual(lhs, rhs, eps); /// <summary> /// Returns a bvec4 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec4 Equal(vec4 lhs, vec4 rhs) => vec4.Equal(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec4 NotEqual(vec4 lhs, vec4 rhs) => vec4.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec4 GreaterThan(vec4 lhs, vec4 rhs) => vec4.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec4 GreaterThanEqual(vec4 lhs, vec4 rhs) => vec4.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec4 LesserThan(vec4 lhs, vec4 rhs) => vec4.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec4 LesserThanEqual(vec4 lhs, vec4 rhs) => vec4.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a bvec4 from component-wise application of IsInfinity (float.IsInfinity(v)). /// </summary> public static bvec4 IsInfinity(vec4 v) => vec4.IsInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsFinite (!float.IsNaN(v) &amp;&amp; !float.IsInfinity(v)). /// </summary> public static bvec4 IsFinite(vec4 v) => vec4.IsFinite(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNaN (float.IsNaN(v)). /// </summary> public static bvec4 IsNaN(vec4 v) => vec4.IsNaN(v); /// <summary> /// Returns a bvec4 from component-wise application of IsNegativeInfinity (float.IsNegativeInfinity(v)). /// </summary> public static bvec4 IsNegativeInfinity(vec4 v) => vec4.IsNegativeInfinity(v); /// <summary> /// Returns a bvec4 from component-wise application of IsPositiveInfinity (float.IsPositiveInfinity(v)). /// </summary> public static bvec4 IsPositiveInfinity(vec4 v) => vec4.IsPositiveInfinity(v); /// <summary> /// Returns a vec4 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static vec4 Abs(vec4 v) => vec4.Abs(v); /// <summary> /// Returns a vec4 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static vec4 HermiteInterpolationOrder3(vec4 v) => vec4.HermiteInterpolationOrder3(v); /// <summary> /// Returns a vec4 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static vec4 HermiteInterpolationOrder5(vec4 v) => vec4.HermiteInterpolationOrder5(v); /// <summary> /// Returns a vec4 from component-wise application of Sqr (v * v). /// </summary> public static vec4 Sqr(vec4 v) => vec4.Sqr(v); /// <summary> /// Returns a vec4 from component-wise application of Pow2 (v * v). /// </summary> public static vec4 Pow2(vec4 v) => vec4.Pow2(v); /// <summary> /// Returns a vec4 from component-wise application of Pow3 (v * v * v). /// </summary> public static vec4 Pow3(vec4 v) => vec4.Pow3(v); /// <summary> /// Returns a vec4 from component-wise application of Step (v &gt;= 0f ? 1f : 0f). /// </summary> public static vec4 Step(vec4 v) => vec4.Step(v); /// <summary> /// Returns a vec4 from component-wise application of Sqrt ((float)Math.Sqrt((double)v)). /// </summary> public static vec4 Sqrt(vec4 v) => vec4.Sqrt(v); /// <summary> /// Returns a vec4 from component-wise application of InverseSqrt ((float)(1.0 / Math.Sqrt((double)v))). /// </summary> public static vec4 InverseSqrt(vec4 v) => vec4.InverseSqrt(v); /// <summary> /// Returns a ivec4 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec4 Sign(vec4 v) => vec4.Sign(v); /// <summary> /// Returns a vec4 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static vec4 Max(vec4 lhs, vec4 rhs) => vec4.Max(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static vec4 Min(vec4 lhs, vec4 rhs) => vec4.Min(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Pow ((float)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static vec4 Pow(vec4 lhs, vec4 rhs) => vec4.Pow(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Log ((float)Math.Log((double)lhs, (double)rhs)). /// </summary> public static vec4 Log(vec4 lhs, vec4 rhs) => vec4.Log(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static vec4 Clamp(vec4 v, vec4 min, vec4 max) => vec4.Clamp(v, min, max); /// <summary> /// Returns a vec4 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static vec4 Mix(vec4 min, vec4 max, vec4 a) => vec4.Mix(min, max, a); /// <summary> /// Returns a vec4 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static vec4 Lerp(vec4 min, vec4 max, vec4 a) => vec4.Lerp(min, max, a); /// <summary> /// Returns a vec4 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static vec4 Smoothstep(vec4 edge0, vec4 edge1, vec4 v) => vec4.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a vec4 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static vec4 Smootherstep(vec4 edge0, vec4 edge1, vec4 v) => vec4.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a vec4 from component-wise application of Fma (a * b + c). /// </summary> public static vec4 Fma(vec4 a, vec4 b, vec4 c) => vec4.Fma(a, b, c); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat2x4 OuterProduct(vec4 c, vec2 r) => vec4.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat3x4 OuterProduct(vec4 c, vec3 r) => vec4.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static mat4 OuterProduct(vec4 c, vec4 r) => vec4.OuterProduct(c, r); /// <summary> /// Returns a vec4 from component-wise application of Add (lhs + rhs). /// </summary> public static vec4 Add(vec4 lhs, vec4 rhs) => vec4.Add(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Sub (lhs - rhs). /// </summary> public static vec4 Sub(vec4 lhs, vec4 rhs) => vec4.Sub(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Mul (lhs * rhs). /// </summary> public static vec4 Mul(vec4 lhs, vec4 rhs) => vec4.Mul(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Div (lhs / rhs). /// </summary> public static vec4 Div(vec4 lhs, vec4 rhs) => vec4.Div(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Modulo (lhs % rhs). /// </summary> public static vec4 Modulo(vec4 lhs, vec4 rhs) => vec4.Modulo(lhs, rhs); /// <summary> /// Returns a vec4 from component-wise application of Degrees (Radians-To-Degrees Conversion). /// </summary> public static vec4 Degrees(vec4 v) => vec4.Degrees(v); /// <summary> /// Returns a vec4 from component-wise application of Radians (Degrees-To-Radians Conversion). /// </summary> public static vec4 Radians(vec4 v) => vec4.Radians(v); /// <summary> /// Returns a vec4 from component-wise application of Acos ((float)Math.Acos((double)v)). /// </summary> public static vec4 Acos(vec4 v) => vec4.Acos(v); /// <summary> /// Returns a vec4 from component-wise application of Asin ((float)Math.Asin((double)v)). /// </summary> public static vec4 Asin(vec4 v) => vec4.Asin(v); /// <summary> /// Returns a vec4 from component-wise application of Atan ((float)Math.Atan((double)v)). /// </summary> public static vec4 Atan(vec4 v) => vec4.Atan(v); /// <summary> /// Returns a vec4 from component-wise application of Cos ((float)Math.Cos((double)v)). /// </summary> public static vec4 Cos(vec4 v) => vec4.Cos(v); /// <summary> /// Returns a vec4 from component-wise application of Cosh ((float)Math.Cosh((double)v)). /// </summary> public static vec4 Cosh(vec4 v) => vec4.Cosh(v); /// <summary> /// Returns a vec4 from component-wise application of Exp ((float)Math.Exp((double)v)). /// </summary> public static vec4 Exp(vec4 v) => vec4.Exp(v); /// <summary> /// Returns a vec4 from component-wise application of Log ((float)Math.Log((double)v)). /// </summary> public static vec4 Log(vec4 v) => vec4.Log(v); /// <summary> /// Returns a vec4 from component-wise application of Log2 ((float)Math.Log((double)v, 2)). /// </summary> public static vec4 Log2(vec4 v) => vec4.Log2(v); /// <summary> /// Returns a vec4 from component-wise application of Log10 ((float)Math.Log10((double)v)). /// </summary> public static vec4 Log10(vec4 v) => vec4.Log10(v); /// <summary> /// Returns a vec4 from component-wise application of Floor ((float)Math.Floor(v)). /// </summary> public static vec4 Floor(vec4 v) => vec4.Floor(v); /// <summary> /// Returns a vec4 from component-wise application of Ceiling ((float)Math.Ceiling(v)). /// </summary> public static vec4 Ceiling(vec4 v) => vec4.Ceiling(v); /// <summary> /// Returns a vec4 from component-wise application of Round ((float)Math.Round(v)). /// </summary> public static vec4 Round(vec4 v) => vec4.Round(v); /// <summary> /// Returns a vec4 from component-wise application of Sin ((float)Math.Sin((double)v)). /// </summary> public static vec4 Sin(vec4 v) => vec4.Sin(v); /// <summary> /// Returns a vec4 from component-wise application of Sinh ((float)Math.Sinh((double)v)). /// </summary> public static vec4 Sinh(vec4 v) => vec4.Sinh(v); /// <summary> /// Returns a vec4 from component-wise application of Tan ((float)Math.Tan((double)v)). /// </summary> public static vec4 Tan(vec4 v) => vec4.Tan(v); /// <summary> /// Returns a vec4 from component-wise application of Tanh ((float)Math.Tanh((double)v)). /// </summary> public static vec4 Tanh(vec4 v) => vec4.Tanh(v); /// <summary> /// Returns a vec4 from component-wise application of Truncate ((float)Math.Truncate((double)v)). /// </summary> public static vec4 Truncate(vec4 v) => vec4.Truncate(v); /// <summary> /// Returns a vec4 from component-wise application of Fract ((float)(v - Math.Floor(v))). /// </summary> public static vec4 Fract(vec4 v) => vec4.Fract(v); /// <summary> /// Returns a vec4 from component-wise application of Trunc ((long)(v)). /// </summary> public static vec4 Trunc(vec4 v) => vec4.Trunc(v); /// <summary> /// Returns the minimal component of this vector. /// </summary> public static float MinElement(vec4 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static float MaxElement(vec4 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static float Length(vec4 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static float LengthSqr(vec4 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static float Sum(vec4 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static float Norm(vec4 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static float Norm1(vec4 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static float Norm2(vec4 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static float NormMax(vec4 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(vec4 v, double p) => v.NormP(p); /// <summary> /// Returns a copy of this vector with length one (undefined if this has zero length). /// </summary> public static vec4 Normalized(vec4 v) => v.Normalized; /// <summary> /// Returns a copy of this vector with length one (returns zero if length is zero). /// </summary> public static vec4 NormalizedSafe(vec4 v) => v.NormalizedSafe; /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static float Dot(vec4 lhs, vec4 rhs) => vec4.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static float Distance(vec4 lhs, vec4 rhs) => vec4.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static float DistanceSqr(vec4 lhs, vec4 rhs) => vec4.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static vec4 Reflect(vec4 I, vec4 N) => vec4.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static vec4 Refract(vec4 I, vec4 N, float eta) => vec4.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static vec4 FaceForward(vec4 N, vec4 I, vec4 Nref) => vec4.FaceForward(N, I, Nref); /// <summary> /// Returns a vec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static vec4 Random(Random random, vec4 minValue, vec4 maxValue) => vec4.Random(random, minValue, maxValue); /// <summary> /// Returns a vec4 with independent and identically distributed uniform values between 'minValue' and 'maxValue'. /// </summary> public static vec4 RandomUniform(Random random, vec4 minValue, vec4 maxValue) => vec4.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a vec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static vec4 RandomNormal(Random random, vec4 mean, vec4 variance) => vec4.RandomNormal(random, mean, variance); /// <summary> /// Returns a vec4 with independent and identically distributed values according to a normal/Gaussian distribution with specified mean and variance. /// </summary> public static vec4 RandomGaussian(Random random, vec4 mean, vec4 variance) => vec4.RandomGaussian(random, mean, variance); } }
using System; using System.Threading; using System.Diagnostics; namespace Amib.Threading.Internal { #region WorkItem Delegate /// <summary> /// An internal delegate to call when the WorkItem starts or completes /// </summary> internal delegate void WorkItemStateCallback(WorkItem workItem); #endregion #region CanceledWorkItemsGroup class public class CanceledWorkItemsGroup { public readonly static CanceledWorkItemsGroup NotCanceledWorkItemsGroup = new CanceledWorkItemsGroup(); private bool _isCanceled = false; public bool IsCanceled { get { return _isCanceled; } set { _isCanceled = value; } } } #endregion #region IInternalWorkItemResult interface internal interface IInternalWorkItemResult { event WorkItemStateCallback OnWorkItemStarted; event WorkItemStateCallback OnWorkItemCompleted; } #endregion #region IInternalWaitableResult interface internal interface IInternalWaitableResult { /// <summary> /// This method is intent for internal use. /// </summary> IWorkItemResult GetWorkItemResult(); } #endregion #region IHasWorkItemPriority interface public interface IHasWorkItemPriority { WorkItemPriority WorkItemPriority { get; } } #endregion #region WorkItem class /// <summary> /// Holds a callback delegate and the state for that delegate. /// </summary> public class WorkItem : IHasWorkItemPriority { #region WorkItemState enum /// <summary> /// Indicates the state of the work item in the thread pool /// </summary> private enum WorkItemState { InQueue = 0, // Nexts: InProgress, Canceled InProgress = 1, // Nexts: Completed, Canceled Completed = 2, // Stays Completed Canceled = 3, // Stays Canceled } private static bool IsValidStatesTransition(WorkItemState currentState, WorkItemState nextState) { bool valid = false; switch (currentState) { case WorkItemState.InQueue: valid = (WorkItemState.InProgress == nextState) || (WorkItemState.Canceled == nextState); break; case WorkItemState.InProgress: valid = (WorkItemState.Completed == nextState) || (WorkItemState.Canceled == nextState); break; case WorkItemState.Completed: case WorkItemState.Canceled: // Cannot be changed break; default: // Unknown state Debug.Assert(false); break; } return valid; } #endregion #region Fields /// <summary> /// Callback delegate for the callback. /// </summary> private readonly WorkItemCallback _callback; /// <summary> /// State with which to call the callback delegate. /// </summary> private object _state; /// <summary> /// Stores the caller's context /// </summary> #if !(WindowsCE) private readonly CallerThreadContext _callerContext; #endif /// <summary> /// Holds the result of the mehtod /// </summary> private object _result; /// <summary> /// Hold the exception if the method threw it /// </summary> private Exception _exception; /// <summary> /// Hold the state of the work item /// </summary> private WorkItemState _workItemState; /// <summary> /// A ManualResetEvent to indicate that the result is ready /// </summary> private ManualResetEvent _workItemCompleted; /// <summary> /// A reference count to the _workItemCompleted. /// When it reaches to zero _workItemCompleted is Closed /// </summary> private int _workItemCompletedRefCount; /// <summary> /// Represents the result state of the work item /// </summary> private readonly WorkItemResult _workItemResult; /// <summary> /// Work item info /// </summary> private readonly WorkItemInfo _workItemInfo; /// <summary> /// Called when the WorkItem starts /// </summary> private event WorkItemStateCallback _workItemStartedEvent; /// <summary> /// Called when the WorkItem completes /// </summary> private event WorkItemStateCallback _workItemCompletedEvent; /// <summary> /// A reference to an object that indicates whatever the /// WorkItemsGroup has been canceled /// </summary> private CanceledWorkItemsGroup _canceledWorkItemsGroup = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup; /// <summary> /// A reference to an object that indicates whatever the /// SmartThreadPool has been canceled /// </summary> private CanceledWorkItemsGroup _canceledSmartThreadPool = CanceledWorkItemsGroup.NotCanceledWorkItemsGroup; /// <summary> /// The work item group this work item belong to. /// </summary> private readonly IWorkItemsGroup _workItemsGroup; /// <summary> /// The thread that executes this workitem. /// This field is available for the period when the work item is executed, before and after it is null. /// </summary> private Thread _executingThread; #region Performance Counter fields /// <summary> /// The time when the work items is queued. /// Used with the performance counter. /// </summary> private DateTime _queuedTime; /// <summary> /// The time when the work items starts its execution. /// Used with the performance counter. /// </summary> private DateTime _beginProcessTime; /// <summary> /// The time when the work items ends its execution. /// Used with the performance counter. /// </summary> private DateTime _endProcessTime; #endregion #endregion #region Properties public TimeSpan WaitingTime { get { return (_beginProcessTime - _queuedTime); } } public TimeSpan ProcessTime { get { return (_endProcessTime - _beginProcessTime); } } #endregion #region Construction /// <summary> /// Initialize the callback holding object. /// </summary> /// <param name="workItemsGroup">The workItemGroup of the workitem</param> /// <param name="workItemInfo">The WorkItemInfo of te workitem</param> /// <param name="callback">Callback delegate for the callback.</param> /// <param name="state">State with which to call the callback delegate.</param> /// /// We assume that the WorkItem object is created within the thread /// that meant to run the callback public WorkItem( IWorkItemsGroup workItemsGroup, WorkItemInfo workItemInfo, WorkItemCallback callback, object state) { _workItemsGroup = workItemsGroup; _workItemInfo = workItemInfo; #if !(WindowsCE) if (_workItemInfo.UseCallerCallContext || _workItemInfo.UseCallerHttpContext) { _callerContext = CallerThreadContext.Capture(_workItemInfo.UseCallerCallContext, _workItemInfo.UseCallerHttpContext); } #endif _callback = callback; _state = state; _workItemResult = new WorkItemResult(this); Initialize(); } internal void Initialize() { // The _workItemState is changed directly instead of using the SetWorkItemState // method since we don't want to go throught IsValidStateTransition. _workItemState = WorkItemState.InQueue; _workItemCompleted = null; _workItemCompletedRefCount = 0; } internal bool WasQueuedBy(IWorkItemsGroup workItemsGroup) { return (workItemsGroup == _workItemsGroup); } #endregion #region Methods public CanceledWorkItemsGroup CanceledWorkItemsGroup { get { return _canceledWorkItemsGroup; } set { _canceledWorkItemsGroup = value; } } public CanceledWorkItemsGroup CanceledSmartThreadPool { get { return _canceledSmartThreadPool; } set { _canceledSmartThreadPool = value; } } /// <summary> /// Change the state of the work item to in progress if it wasn't canceled. /// </summary> /// <returns> /// Return true on success or false in case the work item was canceled. /// If the work item needs to run a post execute then the method will return true. /// </returns> public bool StartingWorkItem() { _beginProcessTime = DateTime.Now; lock(this) { if (IsCanceled) { bool result = false; if ((_workItemInfo.PostExecuteWorkItemCallback != null) && ((_workItemInfo.CallToPostExecute & CallToPostExecute.WhenWorkItemCanceled) == CallToPostExecute.WhenWorkItemCanceled)) { result = true; } return result; } Debug.Assert(WorkItemState.InQueue == GetWorkItemState()); // No need for a lock yet, only after the state has changed to InProgress _executingThread = Thread.CurrentThread; SetWorkItemState(WorkItemState.InProgress); } return true; } /// <summary> /// Execute the work item and the post execute /// </summary> public void Execute() { CallToPostExecute currentCallToPostExecute = 0; // Execute the work item if we are in the correct state switch(GetWorkItemState()) { case WorkItemState.InProgress: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemNotCanceled; ExecuteWorkItem(); break; case WorkItemState.Canceled: currentCallToPostExecute |= CallToPostExecute.WhenWorkItemCanceled; break; default: Debug.Assert(false); throw new NotSupportedException(); } // Run the post execute as needed if ((currentCallToPostExecute & _workItemInfo.CallToPostExecute) != 0) { PostExecute(); } _endProcessTime = DateTime.Now; } internal void FireWorkItemCompleted() { try { if (null != _workItemCompletedEvent) { _workItemCompletedEvent(this); } } catch // Suppress exceptions {} } internal void FireWorkItemStarted() { try { if (null != _workItemStartedEvent) { _workItemStartedEvent(this); } } catch // Suppress exceptions { } } /// <summary> /// Execute the work item /// </summary> private void ExecuteWorkItem() { #if !(WindowsCE) CallerThreadContext ctc = null; if (null != _callerContext) { ctc = CallerThreadContext.Capture(_callerContext.CapturedCallContext, _callerContext.CapturedHttpContext); CallerThreadContext.Apply(_callerContext); } #endif Exception exception = null; object result = null; try { try { result = _callback(_state); } catch (Exception e) { // Save the exception so we can rethrow it later exception = e; } // Remove the value of the execution thread, so it will not be possible to cancel the work item // since it is already completed. // Cancelling a work item that already completed may cause the abortion of the next work item!!! Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread); if (null == executionThread) { // Oops! we are going to be aborted..., Wait here so we can catch the ThreadAbortException Thread.Sleep(60*1000); // If after 1 minute this thread was not aborted then let it continue working. } } // We must treat the ThreadAbortException or else it will be stored in the exception variable catch (ThreadAbortException tae) { // Check if the work item was cancelled if ((string)tae.ExceptionState == "Cancel") { #if !(WindowsCE) Thread.ResetAbort(); #endif } } #if !(WindowsCE) if (null != _callerContext) { CallerThreadContext.Apply(ctc); } #endif if (!SmartThreadPool.IsWorkItemCanceled) { SetResult(result, exception); } } /// <summary> /// Runs the post execute callback /// </summary> private void PostExecute() { if (null != _workItemInfo.PostExecuteWorkItemCallback) { try { _workItemInfo.PostExecuteWorkItemCallback(_workItemResult); } catch (Exception e) { Debug.Assert(null != e); } } } /// <summary> /// Set the result of the work item to return /// </summary> /// <param name="result">The result of the work item</param> /// <param name="exception">The exception that was throw while the workitem executed, null /// if there was no exception.</param> internal void SetResult(object result, Exception exception) { _result = result; _exception = exception; SignalComplete(false); } /// <summary> /// Returns the work item result /// </summary> /// <returns>The work item result</returns> internal IWorkItemResult GetWorkItemResult() { return _workItemResult; } /// <summary> /// Wait for all work items to complete /// </summary> /// <param name="waitableResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// true when every work item in waitableResults has completed; otherwise false. /// </returns> internal static bool WaitAll( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { if (0 == waitableResults.Length) { return true; } bool success; WaitHandle[] waitHandles = new WaitHandle[waitableResults.Length]; GetWaitHandles(waitableResults, waitHandles); if ((null == cancelWaitHandle) && (waitHandles.Length <= 64)) { success = EventWaitHandle.WaitAll(waitHandles, millisecondsTimeout, exitContext); } else { success = true; int millisecondsLeft = millisecondsTimeout; DateTime start = DateTime.Now; WaitHandle [] whs; if (null != cancelWaitHandle) { whs = new WaitHandle [] { null, cancelWaitHandle }; } else { whs = new WaitHandle [] { null }; } bool waitInfinitely = (Timeout.Infinite == millisecondsTimeout); // Iterate over the wait handles and wait for each one to complete. // We cannot use WaitHandle.WaitAll directly, because the cancelWaitHandle // won't affect it. // Each iteration we update the time left for the timeout. for (int i = 0; i < waitableResults.Length; ++i) { // WaitAny don't work with negative numbers if (!waitInfinitely && (millisecondsLeft < 0)) { success = false; break; } whs[0] = waitHandles[i]; int result = EventWaitHandle.WaitAny(whs, millisecondsLeft, exitContext); if ((result > 0) || (EventWaitHandle.WaitTimeout == result)) { success = false; break; } if(!waitInfinitely) { // Update the time left to wait TimeSpan ts = DateTime.Now - start; millisecondsLeft = millisecondsTimeout - (int)ts.TotalMilliseconds; } } } // Release the wait handles ReleaseWaitHandles(waitableResults); return success; } /// <summary> /// Waits for any of the work items in the specified array to complete, cancel, or timeout /// </summary> /// <param name="waitableResults">Array of work item result objects</param> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or Timeout.Infinite (-1) to wait indefinitely.</param> /// <param name="exitContext"> /// true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it; otherwise, false. /// </param> /// <param name="cancelWaitHandle">A cancel wait handle to interrupt the wait if needed</param> /// <returns> /// The array index of the work item result that satisfied the wait, or WaitTimeout if no work item result satisfied the wait and a time interval equivalent to millisecondsTimeout has passed or the work item has been canceled. /// </returns> internal static int WaitAny( IWaitableResult[] waitableResults, int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { WaitHandle [] waitHandles; if (null != cancelWaitHandle) { waitHandles = new WaitHandle[waitableResults.Length + 1]; GetWaitHandles(waitableResults, waitHandles); waitHandles[waitableResults.Length] = cancelWaitHandle; } else { waitHandles = new WaitHandle[waitableResults.Length]; GetWaitHandles(waitableResults, waitHandles); } int result = EventWaitHandle.WaitAny(waitHandles, millisecondsTimeout, exitContext); // Treat cancel as timeout if (null != cancelWaitHandle) { if (result == waitableResults.Length) { result = EventWaitHandle.WaitTimeout; } } ReleaseWaitHandles(waitableResults); return result; } /// <summary> /// Fill an array of wait handles with the work items wait handles. /// </summary> /// <param name="waitableResults">An array of work item results</param> /// <param name="waitHandles">An array of wait handles to fill</param> private static void GetWaitHandles( IWaitableResult[] waitableResults, WaitHandle [] waitHandles) { for (int i = 0; i < waitableResults.Length; ++i) { WorkItemResult wir = waitableResults[i].GetWorkItemResult() as WorkItemResult; Debug.Assert(null != wir, "All waitableResults must be WorkItemResult objects"); waitHandles[i] = wir.GetWorkItem().GetWaitHandle(); } } /// <summary> /// Release the work items' wait handles /// </summary> /// <param name="waitableResults">An array of work item results</param> private static void ReleaseWaitHandles(IWaitableResult[] waitableResults) { for (int i = 0; i < waitableResults.Length; ++i) { WorkItemResult wir = (WorkItemResult)waitableResults[i].GetWorkItemResult(); wir.GetWorkItem().ReleaseWaitHandle(); } } #endregion #region Private Members private WorkItemState GetWorkItemState() { lock (this) { if (WorkItemState.Completed == _workItemState || WorkItemState.InProgress == _workItemState) { return _workItemState; } if (CanceledSmartThreadPool.IsCanceled || CanceledWorkItemsGroup.IsCanceled) { return WorkItemState.Canceled; } return _workItemState; } } /// <summary> /// Sets the work item's state /// </summary> /// <param name="workItemState">The state to set the work item to</param> private void SetWorkItemState(WorkItemState workItemState) { lock(this) { if (IsValidStatesTransition(_workItemState, workItemState)) { _workItemState = workItemState; } } } /// <summary> /// Signals that work item has been completed or canceled /// </summary> /// <param name="canceled">Indicates that the work item has been canceled</param> private void SignalComplete(bool canceled) { SetWorkItemState(canceled ? WorkItemState.Canceled : WorkItemState.Completed); lock(this) { // If someone is waiting then signal. if (null != _workItemCompleted) { _workItemCompleted.Set(); } } } internal void WorkItemIsQueued() { _queuedTime = DateTime.Now; } #endregion #region Members exposed by WorkItemResult /// <summary> /// Cancel the work item if it didn't start running yet. /// </summary> /// <returns>Returns true on success or false if the work item is in progress or already completed</returns> private bool Cancel(bool abortExecution) { #if (WindowsCE) if(abortExecution) { throw new ArgumentOutOfRangeException("abortExecution", "WindowsCE doesn't support this feature"); } #endif bool success = false; bool signalComplete = false; lock (this) { switch(GetWorkItemState()) { case WorkItemState.Canceled: //Debug.WriteLine("Work item already canceled"); success = true; break; case WorkItemState.Completed: //Debug.WriteLine("Work item cannot be canceled"); break; case WorkItemState.InProgress: if (abortExecution) { Thread executionThread = Interlocked.CompareExchange(ref _executingThread, null, _executingThread); if (null != executionThread) { executionThread.Abort("Cancel"); success = true; signalComplete = true; } } else { success = true; signalComplete = true; } break; case WorkItemState.InQueue: // Signal to the wait for completion that the work // item has been completed (canceled). There is no // reason to wait for it to get out of the queue signalComplete = true; //Debug.WriteLine("Work item canceled"); success = true; break; } if (signalComplete) { SignalComplete(true); } } return success; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the method throws and exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { Exception e; object result = GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e); if (null != e) { throw new WorkItemResultException("The work item caused an excpetion, see the inner exception for details", e); } return result; } /// <summary> /// Get the result of the work item. /// If the work item didn't run yet then the caller waits for the result, timeout, or cancel. /// In case of error the e argument is filled with the exception /// </summary> /// <returns>The result of the work item</returns> private object GetResult( int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { e = null; // Check for cancel if (WorkItemState.Canceled == GetWorkItemState()) { throw new WorkItemCancelException("Work item canceled"); } // Check for completion if (IsCompleted) { e = _exception; return _result; } // If no cancelWaitHandle is provided if (null == cancelWaitHandle) { WaitHandle wh = GetWaitHandle(); bool timeout = !wh.WaitOne(millisecondsTimeout, exitContext); ReleaseWaitHandle(); if (timeout) { throw new WorkItemTimeoutException("Work item timeout"); } } else { WaitHandle wh = GetWaitHandle(); int result = EventWaitHandle.WaitAny(new WaitHandle[] { wh, cancelWaitHandle }); ReleaseWaitHandle(); switch(result) { case 0: // The work item signaled // Note that the signal could be also as a result of canceling the // work item (not the get result) break; case 1: case EventWaitHandle.WaitTimeout: throw new WorkItemTimeoutException("Work item timeout"); default: Debug.Assert(false); break; } } // Check for cancel if (WorkItemState.Canceled == GetWorkItemState()) { throw new WorkItemCancelException("Work item canceled"); } Debug.Assert(IsCompleted); e = _exception; // Return the result return _result; } /// <summary> /// A wait handle to wait for completion, cancel, or timeout /// </summary> private WaitHandle GetWaitHandle() { lock(this) { if (null == _workItemCompleted) { _workItemCompleted = EventWaitHandleFactory.CreateManualResetEvent(IsCompleted); } ++_workItemCompletedRefCount; } return _workItemCompleted; } private void ReleaseWaitHandle() { lock(this) { if (null != _workItemCompleted) { --_workItemCompletedRefCount; if (0 == _workItemCompletedRefCount) { _workItemCompleted.Close(); _workItemCompleted = null; } } } } /// <summary> /// Returns true when the work item has completed or canceled /// </summary> private bool IsCompleted { get { lock(this) { WorkItemState workItemState = GetWorkItemState(); return ((workItemState == WorkItemState.Completed) || (workItemState == WorkItemState.Canceled)); } } } /// <summary> /// Returns true when the work item has canceled /// </summary> public bool IsCanceled { get { lock(this) { return (GetWorkItemState() == WorkItemState.Canceled); } } } #endregion #region IHasWorkItemPriority Members /// <summary> /// Returns the priority of the work item /// </summary> public WorkItemPriority WorkItemPriority { get { return _workItemInfo.WorkItemPriority; } } #endregion internal event WorkItemStateCallback OnWorkItemStarted { add { _workItemStartedEvent += value; } remove { _workItemStartedEvent -= value; } } internal event WorkItemStateCallback OnWorkItemCompleted { add { _workItemCompletedEvent += value; } remove { _workItemCompletedEvent -= value; } } #region WorkItemResult class private class WorkItemResult : IWorkItemResult, IInternalWorkItemResult, IInternalWaitableResult { /// <summary> /// A back reference to the work item /// </summary> private readonly WorkItem _workItem; public WorkItemResult(WorkItem workItem) { _workItem = workItem; } internal WorkItem GetWorkItem() { return _workItem; } #region IWorkItemResult Members public bool IsCompleted { get { return _workItem.IsCompleted; } } public bool IsCanceled { get { return _workItem.IsCanceled; } } public object GetResult() { return _workItem.GetResult(Timeout.Infinite, true, null); } public object GetResult(int millisecondsTimeout, bool exitContext) { return _workItem.GetResult(millisecondsTimeout, exitContext, null); } public object GetResult(TimeSpan timeout, bool exitContext) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null); } public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle) { return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle); } public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle); } public object GetResult(out Exception e) { return _workItem.GetResult(Timeout.Infinite, true, null, out e); } public object GetResult(int millisecondsTimeout, bool exitContext, out Exception e) { return _workItem.GetResult(millisecondsTimeout, exitContext, null, out e); } public object GetResult(TimeSpan timeout, bool exitContext, out Exception e) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, null, out e); } public object GetResult(int millisecondsTimeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { return _workItem.GetResult(millisecondsTimeout, exitContext, cancelWaitHandle, out e); } public object GetResult(TimeSpan timeout, bool exitContext, WaitHandle cancelWaitHandle, out Exception e) { return _workItem.GetResult((int)timeout.TotalMilliseconds, exitContext, cancelWaitHandle, out e); } public bool Cancel() { return Cancel(false); } public bool Cancel(bool abortExecution) { return _workItem.Cancel(abortExecution); } public object State { get { return _workItem._state; } } public WorkItemPriority WorkItemPriority { get { return _workItem._workItemInfo.WorkItemPriority; } } /// <summary> /// Return the result, same as GetResult() /// </summary> public object Result { get { return GetResult(); } } /// <summary> /// Returns the exception if occured otherwise returns null. /// This value is valid only after the work item completed, /// before that it is always null. /// </summary> public object Exception { get { return _workItem._exception; } } #endregion #region IInternalWorkItemResult Members public event WorkItemStateCallback OnWorkItemStarted { add { _workItem.OnWorkItemStarted += value; } remove { _workItem.OnWorkItemStarted -= value; } } public event WorkItemStateCallback OnWorkItemCompleted { add { _workItem.OnWorkItemCompleted += value; } remove { _workItem.OnWorkItemCompleted -= value; } } #endregion #region IInternalWorkItemResult Members public IWorkItemResult GetWorkItemResult() { return this; } public IWorkItemResult<TResult> GetWorkItemResultT<TResult>() { return new WorkItemResultTWrapper<TResult>(this); } #endregion } #endregion public void DisposeOfState() { if (_workItemInfo.DisposeOfStateObjects) { IDisposable disp = _state as IDisposable; if (null != disp) { disp.Dispose(); _state = null; } } } } #endregion }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNameSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public GenericNameSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new GenericNameSignatureHelpProvider(); } #region "Declaring generic type objects" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericTerminated() { var markup = @" class G<T> { }; class C { void Foo() { G<G<int>$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterTerminated() { var markup = @" class G<T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS. Also see <see cref=""T""/></typeparam> /// <typeparam name=""T"">TypeParamT</typeparam> class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamS. Also see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS</typeparam> /// <typeparam name=""T"">TypeParamT. Also see <see cref=""S""/></typeparam> class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Constraints on generic types" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsStruct() { var markup = @" class G<S> where S : struct { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : struct", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsClass() { var markup = @" class G<S> where S : class { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : class", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsNew() { var markup = @" class G<S> where S : new() { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : new()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBase() { var markup = @" class Base { } class G<S> where S : Base { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<S> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<S>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<int> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<int>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { var markup = @" class Base<T> { } class G<S> where S : Base<Base<int>> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<Base<int>>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { var markup = @" class G<S, T> where S : T { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : T", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed1() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed2() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<bar, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where T : class, S, IFoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Generic member invocation" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterTerminated() { var markup = @" class C { void Foo<T>() { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1() { var markup = @" class C { /// <summary> /// Method summary /// </summary> /// <typeparam name=""S"" > type param S. see <see cref=""T""/> </typeparam> /// <typeparam name=""T"">type param T. </typeparam> /// <param name=""s"">parameter s</param> /// <param name=""t"">parameter t</param> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "Method summary", "type param S. see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2() { var markup = @" class C { void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericExtensionMethod() { var markup = @" class G { }; class C { void Bar() { G g = null; g.[|Foo<$$|]> } } static class FooClass { public static void Foo<T>(this G g) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void G.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion #region "Constraints on generic methods" [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed1() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where S : Base, new()", "FooSummary", "ParamS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed2() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<Base, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where T : class, S, IFoo, new()", "FooSummary", "ParamT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '<' }; char[] unexpectedCharacters = { ' ', '[', '(' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif void foo() { var x = new D<$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif #if BAR void foo() { var x = new D<$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAlways() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableNever() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAdvanced() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } #endregion [WorkItem(1083601)] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { var markup = @" class G<T> { }; class C { void Foo() { G{$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } } }
//--------------------------------------------------------------------------- // // File: HtmlFromXamlConverter.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Prototype for Xaml - Html conversion // //--------------------------------------------------------------------------- using System; using System.Diagnostics; using System.IO; using System.Text; using System.Xml; namespace Gherkin.Model.HtmlConverter { /// <summary> /// HtmlToXamlConverter is a static class that takes an HTML string /// and converts it into XAML /// </summary> internal static class HtmlFromXamlConverter { // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// Main entry point for Xaml-to-Html converter. /// Converts a xaml string into html string. /// </summary> /// <param name="xamlString"> /// Xaml strinng to convert. /// </param> /// <returns> /// Html string produced from a source xaml. /// </returns> internal static string ConvertXamlToHtml(string xamlString) { XmlTextReader xamlReader; StringBuilder htmlStringBuilder; XmlTextWriter htmlWriter; xamlReader = new XmlTextReader(new StringReader(xamlString)); htmlStringBuilder = new StringBuilder(100); htmlWriter = new XmlTextWriter(new StringWriter(htmlStringBuilder)); if (!WriteFlowDocument(xamlReader, htmlWriter)) { return ""; } string htmlString = htmlStringBuilder.ToString(); return htmlString; } #endregion Internal Methods // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods /// <summary> /// Processes a root level element of XAML (normally it's FlowDocument element). /// </summary> /// <param name="xamlReader"> /// XmlTextReader for a source xaml. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter producing resulting html /// </param> private static bool WriteFlowDocument(XmlTextReader xamlReader, XmlTextWriter htmlWriter) { if (!ReadNextToken(xamlReader)) { // Xaml content is empty - nothing to convert return false; } if (xamlReader.NodeType != XmlNodeType.Element || xamlReader.Name != "FlowDocument") { // Root FlowDocument elemet is missing return false; } // Create a buffer StringBuilder for collecting css properties for inline STYLE attributes // on every element level (it will be re-initialized on every level). StringBuilder inlineStyle = new StringBuilder(); htmlWriter.WriteStartElement("HTML"); htmlWriter.WriteStartElement("BODY"); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); htmlWriter.WriteEndElement(); return true; } /// <summary> /// Reads attributes of the current xaml element and converts /// them into appropriate html attributes or css styles. /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// The reader will remain at the same level after function complete. /// </param> /// <param name="htmlWriter"> /// XmlTextWriter for output html, which is expected to be in /// after WriteStartElement state. /// </param> /// <param name="inlineStyle"> /// String builder for collecting css properties for inline STYLE attribute. /// </param> private static void WriteFormattingProperties(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); // Clear string builder for the inline style inlineStyle.Remove(0, inlineStyle.Length); if (!xamlReader.HasAttributes) { return; } bool borderSet = false; while (xamlReader.MoveToNextAttribute()) { string css = null; switch (xamlReader.Name) { // Character fomatting properties // ------------------------------ case "Background": css = "background-color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "FontFamily": css = "font-family:" + xamlReader.Value + ";"; break; case "FontStyle": css = "font-style:" + xamlReader.Value.ToLower() + ";"; break; case "FontWeight": css = "font-weight:" + xamlReader.Value.ToLower() + ";"; break; case "FontStretch": break; case "FontSize": css = "font-size:" + xamlReader.Value + ";"; break; case "Foreground": css = "color:" + ParseXamlColor(xamlReader.Value) + ";"; break; case "TextDecorations": css = "text-decoration:underline;"; break; case "TextEffects": break; case "Emphasis": break; case "StandardLigatures": break; case "Variants": break; case "Capitals": break; case "Fraction": break; // Paragraph formatting properties // ------------------------------- case "Padding": css = "padding:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "Margin": css = "margin:" + ParseXamlThickness(xamlReader.Value) + ";"; break; case "BorderThickness": css = "border-width:" + ParseXamlThickness(xamlReader.Value) + ";"; borderSet = true; break; case "BorderBrush": css = "border-color:" + ParseXamlColor(xamlReader.Value) + ";"; borderSet = true; break; case "LineHeight": break; case "TextIndent": css = "text-indent:" + xamlReader.Value + ";"; break; case "TextAlignment": css = "text-align:" + xamlReader.Value + ";"; break; case "IsKeptTogether": break; case "IsKeptWithNext": break; case "ColumnBreakBefore": break; case "PageBreakBefore": break; case "FlowDirection": break; // Table attributes // ---------------- case "Width": css = "width:" + xamlReader.Value + ";"; break; case "ColumnSpan": htmlWriter.WriteAttributeString("COLSPAN", xamlReader.Value); break; case "RowSpan": htmlWriter.WriteAttributeString("ROWSPAN", xamlReader.Value); break; } if (css != null) { inlineStyle.Append(css); } } if (borderSet) { inlineStyle.Append("border-style:solid;mso-element:para-border-div;"); } // Return the xamlReader back to element level xamlReader.MoveToElement(); Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); } private static string ParseXamlColor(string color) { if (color.StartsWith("#")) { // Remove transparancy value color = "#" + color.Substring(3); } return color; } private static string ParseXamlThickness(string thickness) { string[] values = thickness.Split(','); for (int i = 0; i < values.Length; i++) { double value; if (double.TryParse(values[i], out value)) { values[i] = Math.Ceiling(value).ToString(); } else { values[i] = "1"; } } string cssThickness; switch (values.Length) { case 1: cssThickness = thickness; break; case 2: cssThickness = values[1] + " " + values[0]; break; case 4: cssThickness = values[1] + " " + values[2] + " " + values[3] + " " + values[0]; break; default: cssThickness = values[0]; break; } return cssThickness; } /// <summary> /// Reads a content of current xaml element, converts it /// </summary> /// <param name="xamlReader"> /// XmlTextReader which is expected to be at XmlNodeType.Element /// (opening element tag) position. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping the xaml element; /// witout producing any output to html. /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attribute. /// </param> private static void WriteElementContent(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); bool elementContentStarted = false; if (xamlReader.IsEmptyElement) { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; } else { while (ReadNextToken(xamlReader) && xamlReader.NodeType != XmlNodeType.EndElement) { switch (xamlReader.NodeType) { case XmlNodeType.Element: if (xamlReader.Name.Contains(".")) { AddComplexProperty(xamlReader, inlineStyle); } else { if (htmlWriter != null && !elementContentStarted && inlineStyle.Length > 0) { // Output STYLE attribute and clear inlineStyle buffer. htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); inlineStyle.Remove(0, inlineStyle.Length); } elementContentStarted = true; WriteElement(xamlReader, htmlWriter, inlineStyle); } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement || xamlReader.NodeType == XmlNodeType.Element && xamlReader.IsEmptyElement); break; case XmlNodeType.Comment: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteComment(xamlReader.Value); } elementContentStarted = true; break; case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: if (htmlWriter != null) { if (!elementContentStarted && inlineStyle.Length > 0) { htmlWriter.WriteAttributeString("STYLE", inlineStyle.ToString()); } htmlWriter.WriteString(xamlReader.Value); } elementContentStarted = true; break; } } Debug.Assert(xamlReader.NodeType == XmlNodeType.EndElement); } } /// <summary> /// Conberts an element notation of complex property into /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="inlineStyle"> /// StringBuilder containing a value for STYLE attribute. /// </param> private static void AddComplexProperty(XmlTextReader xamlReader, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (inlineStyle != null && xamlReader.Name.EndsWith(".TextDecorations")) { inlineStyle.Append("text-decoration:underline;"); } // Skip the element representing the complex property WriteElementContent(xamlReader, /*htmlWriter:*/null, /*inlineStyle:*/null); } /// <summary> /// Converts a xaml element into an appropriate html element. /// </summary> /// <param name="xamlReader"> /// On entry this XmlTextReader must be on Element start tag; /// on exit - on EndElement tag. /// </param> /// <param name="htmlWriter"> /// May be null, in which case we are skipping xaml content /// without producing any html output /// </param> /// <param name="inlineStyle"> /// StringBuilder used for collecting css properties for inline STYLE attributes on every level. /// </param> private static void WriteElement(XmlTextReader xamlReader, XmlTextWriter htmlWriter, StringBuilder inlineStyle) { Debug.Assert(xamlReader.NodeType == XmlNodeType.Element); if (htmlWriter == null) { // Skipping mode; recurse into the xaml element without any output WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } else { string htmlElementName = null; switch (xamlReader.Name) { case "Run": case "Span": htmlElementName = "SPAN"; break; case "InlineUIContainer": htmlElementName = "SPAN"; break; case "Bold": htmlElementName = "B"; break; case "Italic": htmlElementName = "I"; break; case "Paragraph": htmlElementName = "P"; break; case "BlockUIContainer": htmlElementName = "DIV"; break; case "Section": htmlElementName = "DIV"; break; case "Table": htmlElementName = "TABLE"; break; case "TableColumn": htmlElementName = "COL"; break; case "TableRowGroup": htmlElementName = "TBODY"; break; case "TableRow": htmlElementName = "TR"; break; case "TableCell": htmlElementName = "TD"; break; case "List": string marker = xamlReader.GetAttribute("MarkerStyle"); if (marker == null || marker == "None" || marker == "Disc" || marker == "Circle" || marker == "Square" || marker == "Box") { htmlElementName = "UL"; } else { htmlElementName = "OL"; } break; case "ListItem": htmlElementName = "LI"; break; default: htmlElementName = null; // Ignore the element break; } if (htmlWriter != null && htmlElementName != null) { htmlWriter.WriteStartElement(htmlElementName); WriteFormattingProperties(xamlReader, htmlWriter, inlineStyle); WriteElementContent(xamlReader, htmlWriter, inlineStyle); htmlWriter.WriteEndElement(); } else { // Skip this unrecognized xaml element WriteElementContent(xamlReader, /*htmlWriter:*/null, null); } } } // Reader advance helpers // ---------------------- /// <summary> /// Reads several items from xamlReader skipping all non-significant stuff. /// </summary> /// <param name="xamlReader"> /// XmlTextReader from tokens are being read. /// </param> /// <returns> /// True if new token is available; false if end of stream reached. /// </returns> private static bool ReadNextToken(XmlReader xamlReader) { while (xamlReader.Read()) { Debug.Assert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")"); switch (xamlReader.NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: case XmlNodeType.None: case XmlNodeType.CDATA: case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: return true; case XmlNodeType.Whitespace: if (xamlReader.XmlSpace == XmlSpace.Preserve) { return true; } // ignore insignificant whitespace break; case XmlNodeType.EndEntity: case XmlNodeType.EntityReference: // Implement entity reading //xamlReader.ResolveEntity(); //xamlReader.Read(); //ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo); break; // for now we ignore entities as insignificant stuff case XmlNodeType.Comment: return true; case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: case XmlNodeType.XmlDeclaration: default: // Ignorable stuff break; } } return false; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields #endregion Private Fields } }
// MetadataImporter.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using ScriptSharp; using ScriptSharp.Importer.IL; using ScriptSharp.ScriptModel; using ICustomAttributeProvider = ScriptSharp.Importer.IL.ICustomAttributeProvider; namespace ScriptSharp.Importer { internal sealed class MetadataImporter { private SymbolSet _symbols; private CompilerOptions _options; private IErrorHandler _errorHandler; private List<TypeSymbol> _importedTypes; private bool _resolveError; public MetadataImporter(CompilerOptions options, IErrorHandler errorHandler) { Debug.Assert(options != null); Debug.Assert(errorHandler != null); _options = options; _errorHandler = errorHandler; } private ICollection<TypeSymbol> ImportAssemblies(MetadataSource mdSource) { _importedTypes = new List<TypeSymbol>(); ImportScriptAssembly(mdSource, mdSource.CoreAssemblyPath, /* coreAssembly */ true); foreach (TypeSymbol typeSymbol in _importedTypes) { if ((typeSymbol.Type == SymbolType.Class) && (typeSymbol.Name.Equals("Array", StringComparison.Ordinal))) { // Array is special - it is used to build other Arrays of more // specific types we load members for in the second pass... ImportMembers(typeSymbol); } } foreach (TypeSymbol typeSymbol in _importedTypes) { if (typeSymbol.IsGeneric) { // Generics are also special - they are used to build other generic instances // with specific types for generic arguments as we load members for other // types subsequently... ImportMembers(typeSymbol); } } foreach (TypeSymbol typeSymbol in _importedTypes) { if ((typeSymbol.IsGeneric == false) && ((typeSymbol.Type != SymbolType.Class) || (typeSymbol.Name.Equals("Array", StringComparison.Ordinal) == false))) { ImportMembers(typeSymbol); } // There is some special-case logic to be performed on some members of the // global namespace. if (typeSymbol.Type == SymbolType.Class) { if (typeSymbol.Name.Equals("Script", StringComparison.Ordinal)) { // The Script class contains additional pseudo global methods that cannot // be referenced at compile-time by the app author, but can be // referenced by generated code during compilation. ImportPseudoMembers(PseudoClassMembers.Script, (ClassSymbol)typeSymbol); } else if (typeSymbol.Name.Equals("Object", StringComparison.Ordinal)) { // We need to add a static GetType method ImportPseudoMembers(PseudoClassMembers.Object, (ClassSymbol)typeSymbol); } else if (typeSymbol.Name.Equals("Dictionary", StringComparison.Ordinal)) { // The Dictionary class contains static methods at runtime, rather // than instance methods. ImportPseudoMembers(PseudoClassMembers.Dictionary, (ClassSymbol)typeSymbol); } else if (typeSymbol.Name.Equals("Arguments", StringComparison.Ordinal)) { // We need to add a static indexer, which isn't allowed in C# ImportPseudoMembers(PseudoClassMembers.Arguments, (ClassSymbol)typeSymbol); } } } // Import all the types first. // Types need to be loaded upfront so that they can be used in resolving types associated // with members. foreach (string assemblyPath in mdSource.Assemblies) { ImportScriptAssembly(mdSource, assemblyPath, /* coreAssembly */ false); } // Resolve Base Types foreach (TypeSymbol typeSymbol in _importedTypes) { if (typeSymbol.Type == SymbolType.Class) { ImportBaseType((ClassSymbol)typeSymbol); } } // Import members foreach (TypeSymbol typeSymbol in _importedTypes) { if (typeSymbol.IsCoreType) { // already processed above continue; } ImportMembers(typeSymbol); } return _importedTypes; } private void ImportBaseType(ClassSymbol classSymbol) { TypeDefinition type = (TypeDefinition)classSymbol.MetadataReference; TypeReference baseType = type.BaseType; if (baseType != null) { ClassSymbol baseClassSymbol = ResolveType(baseType) as ClassSymbol; if ((baseClassSymbol != null) && (String.CompareOrdinal(baseClassSymbol.FullName, "Object") != 0)) { classSymbol.SetInheritance(baseClassSymbol, /* interfaces */ null); } } } private void ImportDelegateInvoke(TypeSymbol delegateTypeSymbol) { TypeDefinition type = (TypeDefinition)delegateTypeSymbol.MetadataReference; foreach (MethodDefinition method in type.Methods) { if (String.CompareOrdinal(method.Name, "Invoke") != 0) { continue; } TypeSymbol returnType = ResolveType(method.MethodReturnType.ReturnType); Debug.Assert(returnType != null); if (returnType == null) { continue; } MethodSymbol methodSymbol = new MethodSymbol("Invoke", delegateTypeSymbol, returnType, MemberVisibility.Public); methodSymbol.SetImplementationState(SymbolImplementationFlags.Abstract); methodSymbol.SetTransformedName(String.Empty); delegateTypeSymbol.AddMember(methodSymbol); } } private void ImportEnumFields(TypeSymbol enumTypeSymbol) { TypeDefinition type = (TypeDefinition)enumTypeSymbol.MetadataReference; foreach (FieldDefinition field in type.Fields) { if (field.IsSpecialName) { continue; } Debug.Assert(enumTypeSymbol is EnumerationSymbol); EnumerationSymbol enumSymbol = (EnumerationSymbol)enumTypeSymbol; TypeSymbol fieldType; if (enumSymbol.UseNamedValues) { fieldType = _symbols.ResolveIntrinsicType(IntrinsicType.String); } else { fieldType = _symbols.ResolveIntrinsicType(IntrinsicType.Integer); } string fieldName = field.Name; EnumerationFieldSymbol fieldSymbol = new EnumerationFieldSymbol(fieldName, enumTypeSymbol, field.Constant, fieldType); ImportMemberDetails(fieldSymbol, null, field); enumTypeSymbol.AddMember(fieldSymbol); } } private void ImportEvents(TypeSymbol typeSymbol) { TypeDefinition type = (TypeDefinition)typeSymbol.MetadataReference; foreach (EventDefinition eventDef in type.Events) { if (eventDef.IsSpecialName) { continue; } if ((eventDef.AddMethod == null) || (eventDef.RemoveMethod == null)) { continue; } if (eventDef.AddMethod.IsPrivate || eventDef.AddMethod.IsAssembly || eventDef.AddMethod.IsFamilyAndAssembly) { continue; } string eventName = eventDef.Name; TypeSymbol eventHandlerType = ResolveType(eventDef.EventType); if (eventHandlerType == null) { continue; } EventSymbol eventSymbol = new EventSymbol(eventName, typeSymbol, eventHandlerType); ImportMemberDetails(eventSymbol, eventDef.AddMethod, eventDef); string addAccessor; string removeAccessor; if (MetadataHelpers.GetScriptEventAccessors(eventDef, out addAccessor, out removeAccessor)) { eventSymbol.SetAccessors(addAccessor, removeAccessor); } typeSymbol.AddMember(eventSymbol); } } private void ImportFields(TypeSymbol typeSymbol) { TypeDefinition type = (TypeDefinition)typeSymbol.MetadataReference; foreach (FieldDefinition field in type.Fields) { if (field.IsSpecialName) { continue; } if (field.IsPrivate || field.IsAssembly || field.IsFamilyAndAssembly) { continue; } string fieldName = field.Name; TypeSymbol fieldType = ResolveType(field.FieldType); if (fieldType == null) { continue; } MemberVisibility visibility = MemberVisibility.PrivateInstance; if (field.IsStatic) { visibility |= MemberVisibility.Static; } if (field.IsPublic) { visibility |= MemberVisibility.Public; } else if (field.IsFamily || field.IsFamilyOrAssembly) { visibility |= MemberVisibility.Protected; } FieldSymbol fieldSymbol = new FieldSymbol(fieldName, typeSymbol, fieldType); fieldSymbol.SetVisibility(visibility); ImportMemberDetails(fieldSymbol, null, field); typeSymbol.AddMember(fieldSymbol); } } private void ImportMemberDetails(MemberSymbol memberSymbol, MethodDefinition methodDefinition, ICustomAttributeProvider attributeProvider) { if (methodDefinition != null) { MemberVisibility visibility = MemberVisibility.PrivateInstance; if (methodDefinition.IsStatic) { visibility |= MemberVisibility.Static; } if (methodDefinition.IsPublic) { visibility |= MemberVisibility.Public; } else if (methodDefinition.IsFamily || methodDefinition.IsFamilyOrAssembly) { visibility |= MemberVisibility.Protected; } memberSymbol.SetVisibility(visibility); } bool preserveName; bool preserveCase; string scriptName = MetadataHelpers.GetScriptName(attributeProvider, out preserveName, out preserveCase); memberSymbol.SetNameCasing(preserveCase); if (scriptName != null) { memberSymbol.SetTransformedName(scriptName); } // PreserveName is ignored - it only is used for internal members, which are not imported. } private void ImportMembers(TypeSymbol typeSymbol) { switch (typeSymbol.Type) { case SymbolType.Class: case SymbolType.Interface: case SymbolType.Record: if (typeSymbol.Type != SymbolType.Interface) { ImportFields(typeSymbol); } ImportProperties(typeSymbol); ImportMethods(typeSymbol); ImportEvents(typeSymbol); break; case SymbolType.Enumeration: ImportEnumFields(typeSymbol); break; case SymbolType.Delegate: ImportDelegateInvoke(typeSymbol); break; default: Debug.Fail("Unknown symbol type."); break; } } public ICollection<TypeSymbol> ImportMetadata(ICollection<string> references, SymbolSet symbols) { Debug.Assert(references != null); Debug.Assert(symbols != null); _symbols = symbols; MetadataSource mdSource = new MetadataSource(); bool hasLoadErrors = mdSource.LoadReferences(references, _errorHandler); ICollection<TypeSymbol> importedTypes = null; if (hasLoadErrors == false) { importedTypes = ImportAssemblies(mdSource); } if (_resolveError) { return null; } return importedTypes; } private void ImportMethods(TypeSymbol typeSymbol) { // NOTE: We do not import parameters for imported members. // Parameters are used in the script model generation phase to populate // symbol tables, which is not done for imported methods. TypeDefinition type = (TypeDefinition)typeSymbol.MetadataReference; foreach (MethodDefinition method in type.Methods) { if (method.IsSpecialName) { continue; } if (method.IsPrivate || method.IsAssembly || method.IsFamilyAndAssembly) { continue; } string methodName = method.Name; if (typeSymbol.GetMember(methodName) != null) { // Ignore if its an overload since we don't care about parameters // for imported methods, overloaded ctors don't matter. // We just care about return values pretty much, and existence of the // method. continue; } TypeSymbol returnType = ResolveType(method.MethodReturnType.ReturnType); if (returnType == null) { continue; } MethodSymbol methodSymbol = new MethodSymbol(methodName, typeSymbol, returnType); ImportMemberDetails(methodSymbol, method, method); if (method.HasGenericParameters) { List<GenericParameterSymbol> genericArguments = new List<GenericParameterSymbol>(); foreach (GenericParameter genericParameter in method.GenericParameters) { GenericParameterSymbol arg = new GenericParameterSymbol(genericParameter.Position, genericParameter.Name, /* typeArgument */ false, _symbols.GlobalNamespace); genericArguments.Add(arg); } methodSymbol.AddGenericArguments(genericArguments); } if (method.IsAbstract) { // NOTE: We're ignoring the override scenario - it doesn't matter in terms // of the compilation and code generation methodSymbol.SetImplementationState(SymbolImplementationFlags.Abstract); } if (MetadataHelpers.ShouldSkipFromScript(method)) { methodSymbol.SetSkipGeneration(); } string alias = MetadataHelpers.GetScriptAlias(method); if (String.IsNullOrEmpty(alias) == false) { methodSymbol.SetAlias(alias); } string selector = MetadataHelpers.GetScriptMethodSelector(method); if (String.IsNullOrEmpty(selector) == false) { methodSymbol.SetSelector(selector); } ICollection<string> conditions; if (MetadataHelpers.ShouldTreatAsConditionalMethod(method, out conditions)) { methodSymbol.SetConditions(conditions); } typeSymbol.AddMember(methodSymbol); } } private void ImportProperties(TypeSymbol typeSymbol) { TypeDefinition type = (TypeDefinition)typeSymbol.MetadataReference; foreach (PropertyDefinition property in type.Properties) { if (property.IsSpecialName) { continue; } if (property.GetMethod == null) { continue; } if (property.GetMethod.IsPrivate || property.GetMethod.IsAssembly || property.GetMethod.IsFamilyAndAssembly) { continue; } string propertyName = property.Name; bool scriptField = MetadataHelpers.ShouldTreatAsScriptField(property); // TODO: Why are we ignoring the other bits... // bool dummyPreserveName; // bool preserveCase; // string dummyName = MetadataHelpers.GetScriptName(property, out dummyPreserveName, out preserveCase); TypeSymbol propertyType = ResolveType(property.PropertyType); if (propertyType == null) { continue; } PropertySymbol propertySymbol = null; if (property.Parameters.Count != 0) { IndexerSymbol indexerSymbol = new IndexerSymbol(typeSymbol, propertyType); ImportMemberDetails(indexerSymbol, property.GetMethod, property); if (scriptField) { indexerSymbol.SetScriptIndexer(); } propertySymbol = indexerSymbol; // propertySymbol.SetNameCasing(preserveCase); } else { if (scriptField) { // Properties marked with this attribute are to be thought of as // fields. If they are read-only, the C# compiler will enforce that, // so we don't have to worry about making them read-write via a field // instead of a property FieldSymbol fieldSymbol = new FieldSymbol(propertyName, typeSymbol, propertyType); ImportMemberDetails(fieldSymbol, property.GetMethod, property); string alias = MetadataHelpers.GetScriptAlias(property); if (String.IsNullOrEmpty(alias) == false) { fieldSymbol.SetAlias(alias); } typeSymbol.AddMember(fieldSymbol); } else { propertySymbol = new PropertySymbol(propertyName, typeSymbol, propertyType); ImportMemberDetails(propertySymbol, property.GetMethod, property); } } if (propertySymbol != null) { SymbolImplementationFlags implFlags = SymbolImplementationFlags.Regular; if (property.SetMethod == null) { implFlags |= SymbolImplementationFlags.ReadOnly; } if (property.GetMethod.IsAbstract) { implFlags |= SymbolImplementationFlags.Abstract; } propertySymbol.SetImplementationState(implFlags); typeSymbol.AddMember(propertySymbol); } } } private void ImportPseudoMembers(PseudoClassMembers memberSet, ClassSymbol classSymbol) { // Import pseudo members that go on the class but aren't defined in mscorlib.dll // These are meant to be used by internal compiler-generated transformations etc. // and aren't meant to be referenced directly in C# code. if (memberSet == PseudoClassMembers.Script) { TypeSymbol objectType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Object", null, SymbolFilter.Types); Debug.Assert(objectType != null); TypeSymbol stringType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("String", null, SymbolFilter.Types); Debug.Assert(stringType != null); TypeSymbol boolType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Boolean", null, SymbolFilter.Types); Debug.Assert(boolType != null); TypeSymbol dateType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Date", null, SymbolFilter.Types); Debug.Assert(dateType != null); // Enumerate - IEnumerable.GetEnumerator gets mapped to this MethodSymbol enumerateMethod = new MethodSymbol("Enumerate", classSymbol, objectType, MemberVisibility.Public | MemberVisibility.Static); enumerateMethod.SetAlias("ss.enumerate"); enumerateMethod.AddParameter(new ParameterSymbol("obj", enumerateMethod, objectType, ParameterMode.In)); classSymbol.AddMember(enumerateMethod); // TypeName - Type.Name gets mapped to this MethodSymbol typeNameMethod = new MethodSymbol("GetTypeName", classSymbol, stringType, MemberVisibility.Public | MemberVisibility.Static); typeNameMethod.SetAlias("ss.typeName"); typeNameMethod.AddParameter(new ParameterSymbol("obj", typeNameMethod, objectType, ParameterMode.In)); classSymbol.AddMember(typeNameMethod); // CompareDates - Date equality checks get converted to call to compareDates MethodSymbol compareDatesMethod = new MethodSymbol("CompareDates", classSymbol, boolType, MemberVisibility.Public | MemberVisibility.Static); compareDatesMethod.SetAlias("ss.compareDates"); compareDatesMethod.AddParameter(new ParameterSymbol("d1", compareDatesMethod, dateType, ParameterMode.In)); compareDatesMethod.AddParameter(new ParameterSymbol("d2", compareDatesMethod, dateType, ParameterMode.In)); classSymbol.AddMember(compareDatesMethod); return; } if (memberSet == PseudoClassMembers.Arguments) { TypeSymbol objectType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Object", null, SymbolFilter.Types); Debug.Assert(objectType != null); IndexerSymbol indexer = new IndexerSymbol(classSymbol, objectType, MemberVisibility.Public | MemberVisibility.Static); indexer.SetScriptIndexer(); classSymbol.AddMember(indexer); return; } if (memberSet == PseudoClassMembers.Dictionary) { TypeSymbol intType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("Int32", null, SymbolFilter.Types); Debug.Assert(intType != null); TypeSymbol stringType = (TypeSymbol)((ISymbolTable)_symbols.SystemNamespace).FindSymbol("String", null, SymbolFilter.Types); Debug.Assert(stringType != null); // Define Dictionary.Keys MethodSymbol getKeysMethod = new MethodSymbol("GetKeys", classSymbol, _symbols.CreateArrayTypeSymbol(stringType), MemberVisibility.Public | MemberVisibility.Static); getKeysMethod.SetAlias("ss.keys"); classSymbol.AddMember(getKeysMethod); // Define Dictionary.GetCount MethodSymbol countMethod = new MethodSymbol("GetKeyCount", classSymbol, intType, MemberVisibility.Public | MemberVisibility.Static); countMethod.SetAlias("ss.keyCount"); classSymbol.AddMember(countMethod); return; } } private void ImportScriptAssembly(MetadataSource mdSource, string assemblyPath, bool coreAssembly) { string scriptName = null; string scriptIdentifier = null; AssemblyDefinition assembly; if (coreAssembly) { assembly = mdSource.CoreAssemblyMetadata; } else { assembly = mdSource.GetMetadata(assemblyPath); } string scriptNamespace = null; scriptName = MetadataHelpers.GetScriptAssemblyName(assembly, out scriptIdentifier); if (String.IsNullOrEmpty(scriptName) == false) { ScriptReference dependency = new ScriptReference(scriptName, scriptIdentifier); _symbols.AddDependency(dependency); scriptNamespace = dependency.Identifier; } foreach (TypeDefinition type in assembly.MainModule.Types) { try { if (MetadataHelpers.IsCompilerGeneratedType(type)) { continue; } ImportType(mdSource, type, coreAssembly, scriptNamespace); } catch (Exception e) { Debug.Fail(e.ToString()); } } } private void ImportType(MetadataSource mdSource, TypeDefinition type, bool inScriptCoreAssembly, string scriptNamespace) { if (type.IsPublic == false) { return; } if (inScriptCoreAssembly && (MetadataHelpers.ShouldImportScriptCoreType(type) == false)) { return; } string name = type.Name; string namespaceName = type.Namespace; bool dummy; string scriptName = MetadataHelpers.GetScriptName(type, out dummy, out dummy); NamespaceSymbol namespaceSymbol = _symbols.GetNamespace(namespaceName); TypeSymbol typeSymbol = null; if (type.IsInterface) { typeSymbol = new InterfaceSymbol(name, namespaceSymbol); } else if (MetadataHelpers.IsEnum(type)) { // NOTE: We don't care about the flags bit on imported enums // because this is only consumed by the generation logic. typeSymbol = new EnumerationSymbol(name, namespaceSymbol, /* flags */ false); if (MetadataHelpers.ShouldUseEnumNames(type)) { ((EnumerationSymbol)typeSymbol).SetNamedValues(); } else if (MetadataHelpers.ShouldUseEnumValues(type)) { ((EnumerationSymbol)typeSymbol).SetNumericValues(); } } else if (MetadataHelpers.IsDelegate(type)) { typeSymbol = new DelegateSymbol(name, namespaceSymbol); typeSymbol.SetTransformedName("Function"); } else { if (MetadataHelpers.ShouldTreatAsRecordType(type)) { typeSymbol = new RecordSymbol(name, namespaceSymbol); typeSymbol.SetTransformedName("Object"); } else { typeSymbol = new ClassSymbol(name, namespaceSymbol); string extendee; if (MetadataHelpers.IsScriptExtension(type, out extendee)) { ((ClassSymbol)typeSymbol).SetExtenderClass(extendee); } if (String.CompareOrdinal(scriptName, "Array") == 0) { typeSymbol.SetArray(); } } } if (typeSymbol != null) { if (type.HasGenericParameters) { List<GenericParameterSymbol> genericArguments = new List<GenericParameterSymbol>(); foreach (GenericParameter genericParameter in type.GenericParameters) { GenericParameterSymbol arg = new GenericParameterSymbol(genericParameter.Position, genericParameter.Name, /* typeArgument */ true, _symbols.GlobalNamespace); genericArguments.Add(arg); } typeSymbol.AddGenericParameters(genericArguments); } ScriptReference dependency = null; string dependencyIdentifier; string dependencyName = MetadataHelpers.GetScriptDependencyName(type, out dependencyIdentifier); if (dependencyName != null) { dependency = new ScriptReference(dependencyName, dependencyIdentifier); scriptNamespace = dependency.Identifier; } typeSymbol.SetImported(dependency); typeSymbol.SetMetadataToken(type, inScriptCoreAssembly); bool ignoreNamespace = MetadataHelpers.ShouldIgnoreNamespace(type); if (ignoreNamespace || String.IsNullOrEmpty(scriptNamespace)) { typeSymbol.SetIgnoreNamespace(); } else { typeSymbol.ScriptNamespace = scriptNamespace; } typeSymbol.SetPublic(); if (String.IsNullOrEmpty(scriptName) == false) { typeSymbol.SetTransformedName(scriptName); } namespaceSymbol.AddType(typeSymbol); _importedTypes.Add(typeSymbol); } } private TypeSymbol ResolveType(TypeReference type) { int arrayDimensions = 0; while (type is ArrayType) { arrayDimensions++; type = ((ArrayType)type).ElementType; } GenericInstanceType genericType = type as GenericInstanceType; if (genericType != null) { type = genericType.ElementType; } string name = type.FullName; if (String.CompareOrdinal(name, "System.ValueType") == 0) { // Ignore this type - it is the base class for enums, and other primitive types // but we don't import it since it is not useful in script return null; } TypeSymbol typeSymbol; GenericParameter genericParameter = type as GenericParameter; if (genericParameter != null) { typeSymbol = new GenericParameterSymbol(genericParameter.Position, genericParameter.Name, (genericParameter.Owner.GenericParameterType == GenericParameterType.Type), _symbols.GlobalNamespace); } else { typeSymbol = (TypeSymbol)((ISymbolTable)_symbols).FindSymbol(name, null, SymbolFilter.Types); if (typeSymbol == null) { _errorHandler.ReportError("Unable to resolve referenced type '" + name + "'. Make sure all needed assemblies have been explicitly referenced.", String.Empty); _resolveError = true; } } if (genericType != null) { List<TypeSymbol> typeArgs = new List<TypeSymbol>(); foreach (TypeReference argTypeRef in genericType.GenericArguments) { TypeSymbol argType = ResolveType(argTypeRef); typeArgs.Add(argType); } typeSymbol = _symbols.CreateGenericTypeSymbol(typeSymbol, typeArgs); Debug.Assert(typeSymbol != null); } if (arrayDimensions != 0) { for (int i = 0; i < arrayDimensions; i++) { typeSymbol = _symbols.CreateArrayTypeSymbol(typeSymbol); } } return typeSymbol; } private enum PseudoClassMembers { Script, Dictionary, Arguments, Object } } }
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Text; namespace Oranikle.Studio.Controls.NWin32 { /// <summary> /// Windows API Functions /// </summary> public class WindowsAPI { #region Constructors // No need to construct this object private WindowsAPI() { } #endregion #region Constans values public const string TOOLBARCLASSNAME = "ToolbarWindow32"; public const string REBARCLASSNAME = "ReBarWindow32"; public const string PROGRESSBARCLASSNAME = "msctls_progress32"; public const string SCROLLBAR = "SCROLLBAR"; #endregion #region CallBacks public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam); #endregion #region Kernel32.dll functions [DllImport("kernel32.dll", ExactSpelling=true, CharSet=CharSet.Auto)] public static extern int GetCurrentThreadId(); [DllImport("kernel32.dll", ExactSpelling=true, CharSet=CharSet.Auto)] public static extern int GetLastError(); [DllImport("kernel32.dll", ExactSpelling=true, CharSet=CharSet.Auto)] public static extern void SetLastError( int error ); #endregion #region Gdi32.dll functions [DllImport("gdi32.dll")] static public extern bool StretchBlt(IntPtr hDCDest, int XOriginDest, int YOriginDest, int WidthDest, int HeightDest, IntPtr hDCSrc, int XOriginScr, int YOriginSrc, int WidthScr, int HeightScr, uint Rop); [DllImport("gdi32.dll")] static public extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] static public extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int Width, int Heigth); [DllImport("gdi32.dll")] static public extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.dll")] static public extern bool BitBlt(IntPtr hDCDest, int XOriginDest, int YOriginDest, int WidthDest, int HeightDest, IntPtr hDCSrc, int XOriginScr, int YOriginSrc, uint Rop); [DllImport("gdi32.dll")] static public extern IntPtr DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] static public extern bool PatBlt(IntPtr hDC, int XLeft, int YLeft, int Width, int Height, uint Rop); [DllImport("gdi32.dll")] static public extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] static public extern uint GetPixel(IntPtr hDC, int XPos, int YPos); [DllImport("gdi32.dll")] static public extern int SetMapMode(IntPtr hDC, int fnMapMode); [DllImport("gdi32.dll")] static public extern int GetObjectType(IntPtr handle); [DllImport("gdi32")] public static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFO_FLAT bmi, int iUsage, ref int ppvBits, IntPtr hSection, int dwOffset); [DllImport("gdi32")] public static extern int GetDIBits(IntPtr hDC, IntPtr hbm, int StartScan, int ScanLines, int lpBits, BITMAPINFOHEADER bmi, int usage); [DllImport("gdi32")] public static extern int GetDIBits(IntPtr hdc, IntPtr hbm, int StartScan, int ScanLines, int lpBits, ref BITMAPINFO_FLAT bmi, int usage); [DllImport("gdi32")] public static extern IntPtr GetPaletteEntries(IntPtr hpal, int iStartIndex, int nEntries, byte[] lppe); [DllImport("gdi32")] public static extern IntPtr GetSystemPaletteEntries(IntPtr hdc, int iStartIndex, int nEntries, byte[] lppe); [DllImport("gdi32")] public static extern uint SetDCBrushColor(IntPtr hdc, uint crColor); [DllImport("gdi32")] public static extern IntPtr CreateSolidBrush(uint crColor); [DllImport("gdi32")] public static extern int SetBkMode(IntPtr hDC, BackgroundMode mode); [DllImport("gdi32")] public static extern int SetViewportOrgEx(IntPtr hdc, int x, int y, int param); [DllImport("gdi32")] public static extern uint SetTextColor(IntPtr hDC, uint colorRef); [DllImport("gdi32")] public static extern int SetStretchBltMode(IntPtr hDC, int StrechMode); #endregion #region Uxtheme.dll functions [DllImport("uxtheme.dll")] static public extern int SetWindowTheme(IntPtr hWnd, string AppID, string ClassID); #endregion #region User32.dll functions [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern void PostQuitMessage( int exitCode ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr GetDesktopWindow(); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool ShowWindow(IntPtr hWnd, short State); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool UpdateWindow(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool SetForegroundWindow(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, uint flags); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool CloseClipboard(); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool EmptyClipboard(); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr SetClipboardData( uint Format, IntPtr hData); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern bool GetMenuItemRect(IntPtr hWnd, IntPtr hMenu, uint Item, ref RECT rc); [DllImport("user32.dll", ExactSpelling=true, CharSet=CharSet.Auto)] public static extern IntPtr GetParent(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, ref int wParam, ref int lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref MSG lParam ); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage( IntPtr hWnd, int msg, int wParam, ref TOOLINFO lParam ); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, SpinControlMsg msg, int wParam, ref UDACCEL lParam ); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SendMessage(IntPtr hWnd, int msg, int wParam, IntPtr lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref RECT lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref POINT lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TBBUTTON lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TBBUTTONINFO lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref REBARBANDINFO lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref TVITEM lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref LVITEM lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref HDITEM lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern void SendMessage(IntPtr hWnd, int msg, int wParam, ref HD_HITTESTINFO hti); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, ref PARAFORMAT2 format); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int SendDlgItemMessage( IntPtr hWnd, int Id, int msg, int wParam, int lParam ); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr PostMessage(IntPtr hWnd, int msg, int wParam, int lParam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SetWindowsHookEx(int hookid, HookProc pfnhook, IntPtr hinst, int threadid); [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)] public static extern bool UnhookWindowsHookEx(IntPtr hhook); [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)] public static extern IntPtr CallNextHookEx(IntPtr hhook, int code, IntPtr wparam, IntPtr lparam); [DllImport("user32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SetFocus(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static int DrawText(IntPtr hdc, string lpString, int nCount, ref RECT lpRect, int uFormat); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static IntPtr SetParent(IntPtr hChild, IntPtr hParent); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static IntPtr GetDlgItem(IntPtr hDlg, int nControlID); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static int GetClientRect(IntPtr hWnd, ref RECT rc); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static int InvalidateRect(IntPtr hWnd, IntPtr rect, int bErase); [DllImport("user32.dll", CharSet=CharSet.Auto)] public extern static int InvalidateRect(IntPtr hWnd, ref RECT rect, int bErase); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool WaitMessage(); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool PeekMessage(ref MSG msg, int hWnd, uint wFilterMin, uint wFilterMax, uint wFlag); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool GetMessage(ref MSG msg, int hWnd, uint wFilterMin, uint wFilterMax); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool TranslateMessage(ref MSG msg); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool DispatchMessage(ref MSG msg); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr LoadCursor(IntPtr hInstance, uint cursor); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr SetCursor(IntPtr hCursor); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr GetFocus(); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool ReleaseCapture(); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr BeginPaint(IntPtr hWnd, ref PAINTSTRUCT ps); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool EndPaint(IntPtr hWnd, ref PAINTSTRUCT ps); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize, IntPtr hdcSrc, ref POINT pprSrc, Int32 crKey, ref BLENDFUNCTION pblend, Int32 dwFlags); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool ClientToScreen(IntPtr hWnd, ref POINT pt); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool TrackMouseEvent(ref TRACKMOUSEEVENTS tme); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool SetWindowRgn(IntPtr hWnd, IntPtr hRgn, bool redraw); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern ushort GetKeyState(int virtKey); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern bool MoveWindow(IntPtr hWnd, int x, int y, int width, int height, bool repaint); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int GetClassName(IntPtr hWnd, out STRINGBUFFER ClassName, int nMaxCount); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern System.Int32 GetWindowLong( IntPtr hWnd, int nIndex ); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr GetDCEx(IntPtr hWnd, IntPtr hRegion, uint flags); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int FillRect(IntPtr hDC, ref RECT rect, IntPtr hBrush); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT wp); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int SetWindowText(IntPtr hWnd, string text); [DllImport("User32.dll", CharSet=CharSet.Auto)] public static extern int GetWindowText(IntPtr hWnd, out STRINGBUFFER text, int maxCount); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr SetClipboardViewer(IntPtr hWndNewViewer); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int ChangeClipboardChain(IntPtr hWndRemove, IntPtr hWndNewNext); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int GetSystemMetrics(int nIndex); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int SetScrollInfo(IntPtr hwnd, int bar, ref SCROLLINFO si, int fRedraw); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int ShowScrollBar(IntPtr hWnd, int bar, int show); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int EnableScrollBar(IntPtr hWnd, uint flags, uint arrows); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int BringWindowToTop(IntPtr hWnd); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int GetScrollInfo(IntPtr hwnd, int bar, ref SCROLLINFO si); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int ScrollWindowEx(IntPtr hWnd, int dx, int dy, ref RECT rcScroll, ref RECT rcClip, IntPtr UpdateRegion, ref RECT rcInvalidated, uint flags); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int IsWindow(IntPtr hWnd); [DllImport("shell32.Dll", CharSet=CharSet.Auto)] static public extern int Shell_NotifyIcon( NotifyCommand cmd, ref NOTIFYICONDATA data ); [DllImport("User32.Dll", CharSet=CharSet.Auto)] static public extern int TrackPopupMenuEx( IntPtr hMenu, uint uFlags, int x, int y, IntPtr hWnd, IntPtr ignore ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int GetCursorPos( ref POINT pnt ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int GetCaretPos( ref POINT pnt ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int ValidateRect( IntPtr hWnd, ref RECT rc ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr FindWindowEx( IntPtr hWnd, IntPtr hChild, string strClassName, string strName ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern IntPtr FindWindowEx( IntPtr hWnd, IntPtr hChild, string strClassName, IntPtr strName ); [DllImport("user32.dll", CharSet=CharSet.Auto)] static public extern int AnimateWindow( IntPtr hWnd, uint dwTime, uint dwFlags ); #endregion #region Common Controls functions [DllImport("comctl32.dll")] public static extern bool InitCommonControlsEx(INITCOMMONCONTROLSEX icc); [DllImport("comctl32.dll")] public static extern bool InitCommonControls(); [DllImport("comctl32.dll", EntryPoint="DllGetVersion")] public extern static int GetCommonControlDLLVersion(ref DLLVERSIONINFO dvi); [DllImport("comctl32.dll")] public static extern IntPtr ImageList_Create(int width, int height, uint flags, int count, int grow); [DllImport("comctl32.dll")] public static extern bool ImageList_Destroy(IntPtr handle); [DllImport("comctl32.dll")] public static extern int ImageList_Add(IntPtr imageHandle, IntPtr hBitmap, IntPtr hMask); [DllImport("comctl32.dll")] public static extern bool ImageList_Remove(IntPtr imageHandle, int index); [DllImport("comctl32.dll")] public static extern bool ImageList_BeginDrag(IntPtr imageHandle, int imageIndex, int xHotSpot, int yHotSpot); [DllImport("comctl32.dll")] public static extern bool ImageList_DragEnter(IntPtr hWndLock, int x, int y); [DllImport("comctl32.dll")] public static extern bool ImageList_DragMove(int x, int y); [DllImport("comctl32.dll")] public static extern bool ImageList_DragLeave(IntPtr hWndLock); [DllImport("comctl32.dll")] public static extern void ImageList_EndDrag(); #endregion #region Win32 Macro-Like helpers public static int GET_X_LPARAM(int lParam) { return (lParam & 0xffff); } public static int GET_Y_LPARAM(int lParam) { return (lParam >> 16); } public static Point GetPointFromLPARAM(int lParam) { return new Point(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); } public static int LOW_ORDER(int param) { return (param & 0xffff); } public static int HIGH_ORDER(int param) { return (param >> 16); } public static int MAKELONG( int x, int y ) { return (x + ( y << 16 )); } #endregion #region Shell32.Dll [DllImport("shell32.dll")] static public extern IntPtr ShellExecute( IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd ); /// <summary> /// Retrieves a pointer to the Shell's IMalloc interface. /// </summary> /// <param name="hObject">Address of a pointer that receives the Shell's IMalloc interface pointer.</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHGetMalloc( out IntPtr hObject); /// <summary> /// Retrieves the path of a folder as an PIDL. /// </summary> /// <param name="hwndOwner">Handle to the owner window.</param> /// <param name="nFolder">A CSIDL value that identifies the folder to be located</param> /// <param name="hToken">Token that can be used to represent a particular user</param> /// <param name="dwReserved">Reserved</param> /// <param name="ppidl">Address of a pointer to an item identifier list structure specifying the folder's location relative to the root of the namespace (the desktop).</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHGetFolderLocation( IntPtr hwndOwner, Int32 nFolder, IntPtr hToken, UInt32 dwReserved, out IntPtr ppidl); /// <summary> /// Converts an item identifier list to a file system path. /// </summary> /// <param name="pidl">Address of an item identifier list that specifies a file or directory location relative to the root of the namespace (the desktop). </param> /// <param name="pszPath">Address of a buffer to receive the file system path.</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHGetPathFromIDList( IntPtr pidl, StringBuilder pszPath); /// <summary> /// Takes the CSIDL of a folder and returns the pathname. /// </summary> /// <param name="hwndOwner">Handle to an owner window.</param> /// <param name="nFolder">A CSIDL value that identifies the folder whose path is to be retrieved.</param> /// <param name="hToken">An access token that can be used to represent a particular user.</param> /// <param name="dwFlags">Flags to specify which path is to be returned. It is used for cases where the folder associated with a CSIDL may be moved or renamed by the user. </param> /// <param name="pszPath">Pointer to a null-terminated string which will receive the path.</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHGetFolderPath( IntPtr hwndOwner, Int32 nFolder, IntPtr hToken, UInt32 dwFlags, StringBuilder pszPath); /// <summary> /// Translates a Shell namespace object's display name into an item /// identifier list and returns the attributes of the object. This function is /// the preferred method to convert a string to a pointer to an item identifier /// list (PIDL). /// </summary> /// <param name="pszName">Pointer to a zero-terminated wide string that contains the display name to parse. </param> /// <param name="pBndContext">Optional bind context that controls the parsing operation. This parameter is normally set to NULL.</param> /// <param name="ppidl">Address of a pointer to a variable of type ITEMIDLIST that receives the item identifier list for the object.</param> /// <param name="AttrToQuery">ULONG value that specifies the attributes to query.</param> /// <param name="ResultAttr">Pointer to a ULONG. On return, those attributes that are true for the object and were requested in AttrToQuery will be set. </param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHParseDisplayName( [MarshalAs(UnmanagedType.LPWStr)] String pszName, IntPtr pBndContext, out IntPtr ppidl, UInt32 AttrToQuery, out UInt32 ResultAttr); /// <summary> /// Retrieves the IShellFolder interface for the desktop folder, /// which is the root of the Shell's namespace. /// </summary> /// <param name="ppshf">Address that receives an IShellFolder interface pointer for the desktop folder.</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHGetDesktopFolder( out IntPtr ppshf); /// <summary> /// This function takes the fully-qualified pointer to an item /// identifier list (PIDL) of a namespace object, and returns a specified /// interface pointer on the parent object. /// </summary> /// <param name="pidl">The item's PIDL. </param> /// <param name="riid">The REFIID of one of the interfaces exposed by the item's parent object.</param> /// <param name="ppv">A pointer to the interface specified by riid. You must release the object when you are finished.</param> /// <param name="ppidlLast">// The item's PIDL relative to the parent folder. This PIDL can be used with many of the methods supported by the parent folder's interfaces. If you set ppidlLast to NULL, the PIDL will not be returned. </param> /// <returns></returns> [DllImport("shell32.dll")] public static extern Int32 SHBindToParent( IntPtr pidl, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IntPtr ppv, ref IntPtr ppidlLast); /// <summary> /// Accepts a STRRET structure returned by /// ShellFolder::GetDisplayNameOf that contains or points to a string, and then /// returns that string as a BSTR. /// </summary> /// <param name="pstr">Pointer to a STRRET structure.</param> /// <param name="pidl">Pointer to an ITEMIDLIST uniquely identifying a file object or subfolder relative to the parent folder.</param> /// <param name="pbstr">Pointer to a variable of type BSTR that contains the converted string.</param> /// <returns></returns> [DllImport("shlwapi.dll")] public static extern Int32 StrRetToBSTR( ref STRRET pstr, IntPtr pidl, [MarshalAs(UnmanagedType.BStr)] out String pbstr); /// <summary> /// Takes a STRRET structure returned by IShellFolder::GetDisplayNameOf, /// converts it to a string, and places the result in a buffer. /// </summary> /// <param name="pstr">Pointer to the STRRET structure. When the function returns, this pointer will no longer be valid.</param> /// <param name="pidl">Pointer to the item's ITEMIDLIST structure.</param> /// <param name="pszBuf">Buffer to hold the display name. It will be returned as a null-terminated string. If cchBuf is too small, the name will be truncated to fit.</param> /// <param name="cchBuf">Size of pszBuf, in characters. If cchBuf is too small, the string will be truncated to fit. </param> /// <returns></returns> [DllImport("shlwapi.dll")] public static extern Int32 StrRetToBuf( ref STRRET pstr, IntPtr pidl, StringBuilder pszBuf, UInt32 cchBuf); /// <summary> /// Displays a dialog box that enables the user to select a Shell folder. /// </summary> /// <param name="lbpi">// Pointer to a BROWSEINFO structure that contains information used to display the dialog box.</param> /// <returns></returns> [DllImport("shell32.dll")] public static extern IntPtr SHBrowseForFolder( ref BROWSEINFO lbpi); public delegate IntPtr BrowseCallbackProc(IntPtr hwnd, int uMsg, IntPtr lParam, IntPtr lpData); #endregion } }
/*This code is managed under the Apache v2 license. To see an overview: http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0) Author: Robert Gawdzik www.github.com/rgawdzik/ THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Paradox.Menu.GameScreens; using Paradox.Game.Classes.Cameras; using Paradox.Game.Classes.Levels; using Paradox.Game.Classes.Ships; using Paradox.Game.Classes.Engines; namespace Paradox.Game.Classes.Levels { public class Level { #region Variables and Properties List<Collidable> CollidableReference; public TimeSpan TimeRemaining; public bool GameEnded; public event EventHandler StartGame; public event EventHandler WinGame; public event EventHandler LoseGame; private BasicModel[] _asteroidModels; private List<Asteroid> _asteroidList; private Skybox _skybox; private Dock _dock; private Sun _sun; private Planet _levelPlanet; public Starbase PlayerStarBase; public Starbase EnemyStarBase; private Random _randomVar; private float[] _radiusArray; public List<Objective> ObjectiveList; GraphicsDevice _device; List<SoundVoice> _levelSoundVoiceDump; Save _save; public int Score { get; private set; } #endregion #region Constructor public Level(List<Collidable> collidableRef, float[] radiusArray, BasicModel[] asteroidModels, Planet levelPlanet, Starbase playerStarBase, Starbase enemyStarBase, Skybox skybox, Dock dock, Sun sun, PlayerShip pShip, int amtAsteroids, List<Objective> objectiveList, GraphicsDevice device, TimeSpan time, Vector3 minArea, Vector3 maxArea, Save save) { CollidableReference = collidableRef; _radiusArray = radiusArray; _asteroidList = new List<Asteroid>(); _skybox = skybox; _asteroidModels = asteroidModels; _dock = dock; _randomVar = new Random(); for (int i = 0; i < amtAsteroids; i++) { GenerateAsteroid(minArea, maxArea); } _levelSoundVoiceDump = new List<SoundVoice>(); foreach (Objective obj in objectiveList) { obj.Completed += (object sender, EventArgs args) => { //Vector3.Zero is used because position is irrelevant. _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Completed)); }; obj.Failed += (object sender, EventArgs args) => { _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Failed)); }; } pShip.LeftBattlefield += (object sender, EventArgs args) => { _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Leaving)); }; _levelPlanet = levelPlanet; PlayerStarBase = playerStarBase; EnemyStarBase = enemyStarBase; ObjectiveList = objectiveList; _device = device; TimeRemaining = time; _sun = sun; StartGame += (object sender, EventArgs args) => { _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Start)); }; WinGame += (object sender, EventArgs args) => { _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Win)); }; LoseGame += (object sender, EventArgs args) => { _levelSoundVoiceDump.Add(new SoundVoice(SoundType.None, Vector3.Zero, false, SoundVoiceType.Lose)); }; StartGameEvent(); CollidableReference.Add(PlayerStarBase); CollidableReference.Add(EnemyStarBase); CollidableReference.AddRange(_asteroidList); CollidableReference.Add(_dock); foreach(Objective obj in ObjectiveList) { CollidableReference.Add(obj); } _save = save; } #endregion #region Update public void Update(GameTime gameTime, FriendSquadron friendSquadron, EnemySquadron enemySquadron, List<SoundVoice> soundVoiceDump) { Score = enemySquadron.ShipsDestroyedPlayer + enemySquadron.FrigatesDestroyedPlayer; if (_levelSoundVoiceDump.Count > 0) { if (!_levelSoundVoiceDump[0].IsCreated) //These are old sounds, let's ignore em. { _levelSoundVoiceDump.Clear(); } soundVoiceDump.AddRange(_levelSoundVoiceDump); } //Updates each asteroid foreach (Asteroid asteroid in _asteroidList) { asteroid.RotateAsteroid(gameTime); } //Updates the planet _levelPlanet.Update(gameTime); //Updates the Star Bases. PlayerStarBase.Update(); EnemyStarBase.Update(); //Update Objectives foreach (Objective obj in ObjectiveList) { obj.Update(gameTime, enemySquadron, friendSquadron); } if (TimeRemaining > TimeSpan.Zero) { TimeRemaining -= gameTime.ElapsedGameTime; } CheckEndGame(); } #endregion #region Draw public void Draw(Camera camera) { _sun.Draw(camera); //Draws each Asteroid dependant on the type of asteroid they are. This ensures as little memory is used. foreach (Asteroid asteroid in _asteroidList) { _asteroidModels[(int)asteroid.AsteroidType].World = asteroid.World; _asteroidModels[(int)asteroid.AsteroidType].Rotation = asteroid.Rotation; _asteroidModels[(int)asteroid.AsteroidType].DrawModel(camera); } _levelPlanet.DrawPlanet(camera); PlayerStarBase.DrawBase(camera); EnemyStarBase.DrawBase(camera); _dock.Draw(camera); foreach (Objective obj in ObjectiveList) { obj.Draw(_device, camera); } } #endregion #region Helper Methods public void GenerateAsteroid(Vector3 AreaMinimum, Vector3 AreaMaximum) //The two Vector3 coordinates tell the general area of where to spawn asteroids. { //Only the first asteroid is really any good. int randInt = 1; float boundingRadius = _radiusArray[randInt]; _asteroidList.Add(new Asteroid(CollidableType.Asteroid, boundingRadius, (AsteroidType)randInt, new Vector3(_randomVar.Next((int)AreaMinimum.X, (int)AreaMaximum.X), _randomVar.Next((int)AreaMinimum.X, (int)AreaMaximum.X), _randomVar.Next((int)AreaMinimum.X, (int)AreaMaximum.X)), (float)_randomVar.NextDouble())); } public void StartGameEvent() { if (StartGame != null) StartGame(this, EventArgs.Empty); } public void LoseGameEvent() { if (LoseGame != null) LoseGame(this, EventArgs.Empty); } public void WinGameEvent() { if (WinGame != null) WinGame(this, EventArgs.Empty); } public void CheckEndGame() { if (TimeRemaining <= TimeSpan.Zero && !GameEnded) { GameEnded = true; int completedObj = 0; foreach (Objective obj in ObjectiveList) { if (!obj.IsFailed) completedObj++; } //To win the game, the amount of objectives not failed must equal the objective count. if (completedObj == ObjectiveList.Count) { WinGameEvent(); _save.Config.Win = true; _save.Config.End = true; _save.Leaderboards.Add(new Posting("", Score)); } else { LoseGameEvent(); _save.Config.Win = false; _save.Config.End = true; _save.Leaderboards.Add(new Posting("", Score)); } //Let's bring up the endgame menu. EndGameMenu.SelectedEvent(); } } #endregion } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; using Microsoft.Zelig.Test; namespace Microsoft.Zelig.Test { public class OperatorsTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests"); } public override TestResult Run(string[] args) { TestResult result = TestResult.Pass; string testName = "Operators"; result |= Assert.CheckFailed(Operators1_Test(), testName, 1); result |= Assert.CheckFailed(Operators2_Test(), testName, 2); result |= Assert.CheckFailed(Operators3_Test(), testName, 3); result |= Assert.CheckFailed(Operators4_Test(), testName, 4); result |= Assert.CheckFailed(Operators5_Test(), testName, 5); result |= Assert.CheckFailed(Operators6_Test(), testName, 6); result |= Assert.CheckFailed(Operators7_Test(), testName, 7); result |= Assert.CheckFailed(Operators13_Test(), testName, 13); result |= Assert.CheckFailed(Operators14_Test(), testName, 14); result |= Assert.CheckFailed(Operators15_Test(), testName, 15); result |= Assert.CheckFailed(Operators16_Test(), testName, 16); result |= Assert.CheckFailed(Operators17_Test(), testName, 17); result |= Assert.CheckFailed(Operators18_Test(), testName, 18); result |= Assert.CheckFailed(Operators19_Test(), testName, 19); result |= Assert.CheckFailed(Operators20_Test(), testName, 20); result |= Assert.CheckFailed(Operators21_Test(), testName, 21); result |= Assert.CheckFailed(Operators22_Test(), testName, 22); result |= Assert.CheckFailed(Operators23_Test(), testName, 23); result |= Assert.CheckFailed(Operators24_Test(), testName, 24); result |= Assert.CheckFailed(Operators38_Test(), testName, 38); result |= Assert.CheckFailed(Operators39_Test(), testName, 39); result |= Assert.CheckFailed(Operators40_Test(), testName, 40); result |= Assert.CheckFailed(Operators41_Test(), testName, 41); result |= Assert.CheckFailed(Operators42_Test(), testName, 42); result |= Assert.CheckFailed(Operators43_Test(), testName, 43); result |= Assert.CheckFailed(Operators44_Test(), testName, 44); result |= Assert.CheckFailed(Operators45_Test(), testName, 45); result |= Assert.CheckFailed(Operators46_Test(), testName, 46); result |= Assert.CheckFailed(Operators67_Test(), testName, 67); result |= Assert.CheckFailed(Operators68_Test(), testName, 68); result |= Assert.CheckFailed(Operators69_Test(), testName, 69); result |= Assert.CheckFailed(Operators88_Test(), testName, 88); result |= Assert.CheckFailed(Operators89_Test(), testName, 89); result |= Assert.CheckFailed(Operators90_Test(), testName, 90); result |= Assert.CheckFailed(Operators91_Test(), testName, 91); result |= Assert.CheckFailed(Operators92_Test(), testName, 92); result |= Assert.CheckFailed(Operators93_Test(), testName, 93); result |= Assert.CheckFailed(Operators94_Test(), testName, 94); result |= Assert.CheckFailed(Operators95_Test(), testName, 95); result |= Assert.CheckFailed(Operators96_Test(), testName, 96); return result; } //Operators Test methods //All test methods ported from folder current\test\cases\client\CLR\Conformance\10_classes\Operators //The following tests were removed because they were build failure tests: //8-12,26-37,47-66,70-87 [TestMethod] public TestResult Operators1_Test() { Log.Comment("Tests overriding unary plus"); if (OperatorsTestClass1.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators2_Test() { Log.Comment("Tests overriding unary minus"); if (OperatorsTestClass2.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators3_Test() { Log.Comment("Tests overriding tilde"); if (OperatorsTestClass3.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators4_Test() { Log.Comment("Tests overriding increment prefix"); if (OperatorsTestClass4.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators5_Test() { Log.Comment("Tests overriding increment suffix"); if (OperatorsTestClass5.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators6_Test() { Log.Comment("Tests overriding decrement prefix"); if (OperatorsTestClass6.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators7_Test() { Log.Comment("Tests overriding decrement suffix"); if (OperatorsTestClass7.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators13_Test() { Log.Comment("Tests overriding binary plus"); if (OperatorsTestClass13.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators14_Test() { Log.Comment("Tests overriding binary minus"); if (OperatorsTestClass14.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators15_Test() { Log.Comment("Tests overriding asterisk (multiply)"); if (OperatorsTestClass15.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators16_Test() { Log.Comment("Tests overriding slash (division)"); if (OperatorsTestClass16.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators17_Test() { Log.Comment("Tests overriding percent (modulus)"); if (OperatorsTestClass17.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators18_Test() { Log.Comment("Tests overriding caret (xor)"); if (OperatorsTestClass18.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators19_Test() { Log.Comment("Tests overriding ampersand"); if (OperatorsTestClass19.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators20_Test() { Log.Comment("Tests overriding pipe (or)"); if (OperatorsTestClass20.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators21_Test() { Log.Comment("Tests overriding double less-than (left shift)"); if (OperatorsTestClass21.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators22_Test() { Log.Comment("Tests overriding double greater-than (right shift)"); if (OperatorsTestClass22.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators23_Test() { Log.Comment("Tests overriding binary plus with 1 int parameter"); if (OperatorsTestClass23.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators24_Test() { Log.Comment("Tests overriding double equals (equality comparison) and exclamation-equals (non-equality comparison)"); if (OperatorsTestClass24.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators38_Test() { Log.Comment("Tests overriding binary plus with 1 int parameter"); if (OperatorsTestClass38.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators39_Test() { Log.Comment("Tests overriding binary minus with 1 int parameter"); if (OperatorsTestClass39.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators40_Test() { Log.Comment("Tests overriding asterisk (multiply) with 1 int parameter"); if (OperatorsTestClass40.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators41_Test() { Log.Comment("Tests overriding slash (divide) with 1 int parameter"); if (OperatorsTestClass41.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators42_Test() { Log.Comment("Tests overriding percent (modulus) with 1 int parameter"); if (OperatorsTestClass42.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators43_Test() { Log.Comment("Tests overriding caret (xor) with 1 int parameter"); if (OperatorsTestClass43.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators44_Test() { Log.Comment("Tests overriding ampersand with 1 int parameter"); if (OperatorsTestClass44.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators45_Test() { Log.Comment("Tests overriding pipe (or) with 1 int parameter"); if (OperatorsTestClass45.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators46_Test() { Log.Comment("Tests overriding double equals (equality comparison) and exclamation-equals "); Log.Comment("(non-equality comparison) with 1 int"); if (OperatorsTestClass46.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators67_Test() { Log.Comment("Tests overriding unary exclamation (not)"); if (OperatorsTestClass67.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators68_Test() { Log.Comment("Tests overriding true and false"); if (OperatorsTestClass68.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators69_Test() { Log.Comment("Tests overriding true and false and ampersand"); if (OperatorsTestClass69.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators88_Test() { Log.Comment("Tests true and false with ampersand"); if (OperatorsTestClass88.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators89_Test() { Log.Comment("Tests true and false with double ampersand"); if (OperatorsTestClass89.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators90_Test() { Log.Comment("Tests true and false with pipe (or)"); if (OperatorsTestClass90.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators91_Test() { Log.Comment("Tests true and false with double pipe (or)"); if (OperatorsTestClass91.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators92_Test() { Log.Comment("Tests true and false with caret (xor)"); if (OperatorsTestClass92.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators93_Test() { Log.Comment("Tests numerical types with plus"); if (OperatorsTestClass93.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators94_Test() { Log.Comment("Tests numerical types with minus"); if (OperatorsTestClass94.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators95_Test() { Log.Comment("Tests numerical types with asterisk (multiply)"); if (OperatorsTestClass95.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } [TestMethod] public TestResult Operators96_Test() { Log.Comment("Tests numerical types with slash (divide)"); if (OperatorsTestClass96.testMethod()) { return TestResult.Pass; } return TestResult.Fail; } class OperatorsTestClass1 { public int intI = 2; public static OperatorsTestClass1 operator +(OperatorsTestClass1 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass1 Test = new OperatorsTestClass1(); OperatorsTestClass1 temp = +Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass2 { public int intI = 2; public static OperatorsTestClass2 operator -(OperatorsTestClass2 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass2 Test = new OperatorsTestClass2(); OperatorsTestClass2 temp = -Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass3 { public int intI = 2; public static OperatorsTestClass3 operator ~(OperatorsTestClass3 MyInt) { MyInt.intI = 3; return MyInt; } public static bool testMethod() { OperatorsTestClass3 Test = new OperatorsTestClass3(); OperatorsTestClass3 temp = ~Test; if (Test.intI == 3) { return true; } else { return false; } } } class OperatorsTestClass4 { public int intI = 2; public static OperatorsTestClass4 operator ++(OperatorsTestClass4 MyInt) { OperatorsTestClass4 MC = new OperatorsTestClass4(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass4 Test = new OperatorsTestClass4(); OperatorsTestClass4 Test2 = ++Test; if ((Test.intI == 3) && (Test2.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass5 { public int intI = 2; public static OperatorsTestClass5 operator ++(OperatorsTestClass5 MyInt) { OperatorsTestClass5 MC = new OperatorsTestClass5(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass5 Test = new OperatorsTestClass5(); OperatorsTestClass5 Test2 = Test++; if ((Test.intI == 3) && (Test2.intI == 2)) { return true; } else { return false; } } } class OperatorsTestClass6 { public int intI = 2; public static OperatorsTestClass6 operator --(OperatorsTestClass6 MyInt) { OperatorsTestClass6 MC = new OperatorsTestClass6(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass6 Test = new OperatorsTestClass6(); OperatorsTestClass6 Test2 = --Test; if ((Test.intI == 3) && (Test2.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass7 { public int intI = 2; public static OperatorsTestClass7 operator --(OperatorsTestClass7 MyInt) { OperatorsTestClass7 MC = new OperatorsTestClass7(); MC.intI = 3; return MC; } public static bool testMethod() { OperatorsTestClass7 Test = new OperatorsTestClass7(); OperatorsTestClass7 Test2 = Test--; if ((Test.intI == 3) && (Test2.intI == 2)) { return true; } else { return false; } } } class OperatorsTestClass13 { public int intI = 2; public static OperatorsTestClass13 operator +(OperatorsTestClass13 MyInt, OperatorsTestClass13 MyInt2) { OperatorsTestClass13 MC = new OperatorsTestClass13(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass13 Test1 = new OperatorsTestClass13(); OperatorsTestClass13 Test2 = new OperatorsTestClass13(); Test2.intI = 3; OperatorsTestClass13 Test = Test1 + Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass14 { public int intI = 2; public static OperatorsTestClass14 operator -(OperatorsTestClass14 MyInt, OperatorsTestClass14 MyInt2) { OperatorsTestClass14 MC = new OperatorsTestClass14(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass14 Test1 = new OperatorsTestClass14(); OperatorsTestClass14 Test2 = new OperatorsTestClass14(); Test2.intI = 3; OperatorsTestClass14 Test = Test1 - Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass15 { public int intI = 2; public static OperatorsTestClass15 operator *(OperatorsTestClass15 MyInt, OperatorsTestClass15 MyInt2) { OperatorsTestClass15 MC = new OperatorsTestClass15(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass15 Test1 = new OperatorsTestClass15(); OperatorsTestClass15 Test2 = new OperatorsTestClass15(); Test2.intI = 3; OperatorsTestClass15 Test = Test1 * Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass16 { public int intI = 2; public static OperatorsTestClass16 operator /(OperatorsTestClass16 MyInt, OperatorsTestClass16 MyInt2) { OperatorsTestClass16 MC = new OperatorsTestClass16(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass16 Test1 = new OperatorsTestClass16(); OperatorsTestClass16 Test2 = new OperatorsTestClass16(); Test2.intI = 3; OperatorsTestClass16 Test = Test1 / Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass17 { public int intI = 2; public static OperatorsTestClass17 operator %(OperatorsTestClass17 MyInt, OperatorsTestClass17 MyInt2) { OperatorsTestClass17 MC = new OperatorsTestClass17(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass17 Test1 = new OperatorsTestClass17(); OperatorsTestClass17 Test2 = new OperatorsTestClass17(); Test2.intI = 3; OperatorsTestClass17 Test = Test1 % Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass18 { public int intI = 2; public static OperatorsTestClass18 operator ^(OperatorsTestClass18 MyInt, OperatorsTestClass18 MyInt2) { OperatorsTestClass18 MC = new OperatorsTestClass18(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass18 Test1 = new OperatorsTestClass18(); OperatorsTestClass18 Test2 = new OperatorsTestClass18(); Test2.intI = 3; OperatorsTestClass18 Test = Test1 ^ Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass19 { public int intI = 2; public static OperatorsTestClass19 operator &(OperatorsTestClass19 MyInt, OperatorsTestClass19 MyInt2) { OperatorsTestClass19 MC = new OperatorsTestClass19(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass19 Test1 = new OperatorsTestClass19(); OperatorsTestClass19 Test2 = new OperatorsTestClass19(); Test2.intI = 3; OperatorsTestClass19 Test = Test1 & Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass20 { public int intI = 2; public static OperatorsTestClass20 operator |(OperatorsTestClass20 MyInt, OperatorsTestClass20 MyInt2) { OperatorsTestClass20 MC = new OperatorsTestClass20(); MC.intI = MyInt.intI + MyInt2.intI; return MC; } public static bool testMethod() { OperatorsTestClass20 Test1 = new OperatorsTestClass20(); OperatorsTestClass20 Test2 = new OperatorsTestClass20(); Test2.intI = 3; OperatorsTestClass20 Test = Test1 | Test2; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass21 { public int intI = 2; public static OperatorsTestClass21 operator <<(OperatorsTestClass21 MyInt, int MyInt2) { OperatorsTestClass21 MC = new OperatorsTestClass21(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass21 Test1 = new OperatorsTestClass21(); OperatorsTestClass21 Test = Test1 << 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass22 { public int intI = 2; public static OperatorsTestClass22 operator >>(OperatorsTestClass22 MyInt, int MyInt2) { OperatorsTestClass22 MC = new OperatorsTestClass22(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass22 Test1 = new OperatorsTestClass22(); OperatorsTestClass22 Test = Test1 >> 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass23 { public int intI = 2; public static OperatorsTestClass23 operator +(OperatorsTestClass23 MyInt, int MyInt2) { OperatorsTestClass23 MC = new OperatorsTestClass23(); MC.intI = MyInt.intI + MyInt2; return MC; } public static bool testMethod() { OperatorsTestClass23 Test1 = new OperatorsTestClass23(); OperatorsTestClass23 Test = Test1 + 3; if (Test.intI == 5) { return true; } else { return false; } } } class OperatorsTestClass24 { public int intI = 2; public static bool operator ==(OperatorsTestClass24 MyInt, OperatorsTestClass24 MyInt2) { if (MyInt.intI == MyInt2.intI) { return true; } else { return false; } } public static bool operator !=(OperatorsTestClass24 MyInt, OperatorsTestClass24 MyInt2) { return false; } public static bool testMethod() { OperatorsTestClass24 Test1 = new OperatorsTestClass24(); OperatorsTestClass24 Test2 = new OperatorsTestClass24(); OperatorsTestClass24 Test3 = new OperatorsTestClass24(); Test2.intI = 3; if ((Test1 == Test3) && (!(Test1 == Test2))) { return true; } else { return false; } } } class OperatorsTestClass38 { public int intI = 2; public static OperatorsTestClass38 operator +(OperatorsTestClass38 MyInt, int MyInt2) { OperatorsTestClass38 MC = new OperatorsTestClass38(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass38 operator +(int MyInt, OperatorsTestClass38 MyInt2) { OperatorsTestClass38 MC = new OperatorsTestClass38(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass38 Test1 = new OperatorsTestClass38(); OperatorsTestClass38 TestClass1 = Test1 + 1; OperatorsTestClass38 TestClass2 = 1 + Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass39 { public int intI = 2; public static OperatorsTestClass39 operator -(OperatorsTestClass39 MyInt, int MyInt2) { OperatorsTestClass39 MC = new OperatorsTestClass39(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass39 operator -(int MyInt, OperatorsTestClass39 MyInt2) { OperatorsTestClass39 MC = new OperatorsTestClass39(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass39 Test1 = new OperatorsTestClass39(); OperatorsTestClass39 TestClass1 = Test1 - 1; OperatorsTestClass39 TestClass2 = 1 - Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass40 { public int intI = 2; public static OperatorsTestClass40 operator *(OperatorsTestClass40 MyInt, int MyInt2) { OperatorsTestClass40 MC = new OperatorsTestClass40(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass40 operator *(int MyInt, OperatorsTestClass40 MyInt2) { OperatorsTestClass40 MC = new OperatorsTestClass40(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass40 Test1 = new OperatorsTestClass40(); OperatorsTestClass40 TestClass1 = Test1 * 1; OperatorsTestClass40 TestClass2 = 1 * Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass41 { public int intI = 2; public static OperatorsTestClass41 operator /(OperatorsTestClass41 MyInt, int MyInt2) { OperatorsTestClass41 MC = new OperatorsTestClass41(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass41 operator /(int MyInt, OperatorsTestClass41 MyInt2) { OperatorsTestClass41 MC = new OperatorsTestClass41(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass41 Test1 = new OperatorsTestClass41(); OperatorsTestClass41 TestClass1 = Test1 / 1; OperatorsTestClass41 TestClass2 = 1 / Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass42 { public int intI = 2; public static OperatorsTestClass42 operator %(OperatorsTestClass42 MyInt, int MyInt2) { OperatorsTestClass42 MC = new OperatorsTestClass42(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass42 operator %(int MyInt, OperatorsTestClass42 MyInt2) { OperatorsTestClass42 MC = new OperatorsTestClass42(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass42 Test1 = new OperatorsTestClass42(); OperatorsTestClass42 TestClass1 = Test1 % 1; OperatorsTestClass42 TestClass2 = 1 % Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass43 { public int intI = 2; public static OperatorsTestClass43 operator ^(OperatorsTestClass43 MyInt, int MyInt2) { OperatorsTestClass43 MC = new OperatorsTestClass43(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass43 operator ^(int MyInt, OperatorsTestClass43 MyInt2) { OperatorsTestClass43 MC = new OperatorsTestClass43(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass43 Test1 = new OperatorsTestClass43(); OperatorsTestClass43 TestClass1 = Test1 ^ 1; OperatorsTestClass43 TestClass2 = 1 ^ Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass44 { public int intI = 2; public static OperatorsTestClass44 operator &(OperatorsTestClass44 MyInt, int MyInt2) { OperatorsTestClass44 MC = new OperatorsTestClass44(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass44 operator &(int MyInt, OperatorsTestClass44 MyInt2) { OperatorsTestClass44 MC = new OperatorsTestClass44(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass44 Test1 = new OperatorsTestClass44(); OperatorsTestClass44 TestClass1 = Test1 & 1; OperatorsTestClass44 TestClass2 = 1 & Test1; if ((TestClass1.intI == 3) && (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass45 { public int intI = 2; public static OperatorsTestClass45 operator |(OperatorsTestClass45 MyInt, int MyInt2) { OperatorsTestClass45 MC = new OperatorsTestClass45(); MC.intI = MyInt.intI + MyInt2; return MC; } public static OperatorsTestClass45 operator |(int MyInt, OperatorsTestClass45 MyInt2) { OperatorsTestClass45 MC = new OperatorsTestClass45(); MC.intI = MyInt + MyInt2.intI + 1; return MC; } public static bool testMethod() { OperatorsTestClass45 Test1 = new OperatorsTestClass45(); OperatorsTestClass45 TestClass1 = Test1 | 1; OperatorsTestClass45 TestClass2 = 1 | Test1; if ((TestClass1.intI == 3) || (TestClass2.intI == 4)) { return true; } else { return false; } } } class OperatorsTestClass46 { public int intI = 2; public static bool operator ==(OperatorsTestClass46 MyInt, int MyInt2) { return (MyInt.intI != MyInt2); } public static bool operator !=(OperatorsTestClass46 MyInt, int MyInt2) { return false; } public static bool testMethod() { OperatorsTestClass46 Test1 = new OperatorsTestClass46(); if (((Test1 == 2) == false) && ((Test1 == 4) == true)) { return true; } else { return false; } } } class OperatorsTestClass67 { public int intI = 2; public static bool operator !(OperatorsTestClass67 MyInt) { MyInt.intI = 3; return true; } public static bool testMethod() { OperatorsTestClass67 Test = new OperatorsTestClass67(); if ((!Test) && (Test.intI == 3)) { return true; } else { return false; } } } class OperatorsTestClass68 { public int intI = 2; public static bool operator true(OperatorsTestClass68 MyInt) { MyInt.intI = 3; return true; } public static bool operator false(OperatorsTestClass68 MyInt) { MyInt.intI = 4; return false; } public static bool testMethod() { OperatorsTestClass68 Test = new OperatorsTestClass68(); if (Test) { if (Test.intI == 3) { return true; } return false; } else { return false; } } } class OperatorsTestClass69 { public int intI = 2; public static bool operator true(OperatorsTestClass69 MyInt) { MyInt.intI = 3; return true; } public static bool operator false(OperatorsTestClass69 MyInt) { MyInt.intI = 4; return false; } public static OperatorsTestClass69 operator &(OperatorsTestClass69 mc1, OperatorsTestClass69 mc2) { return new OperatorsTestClass69(); } public static bool testMethod() { OperatorsTestClass69 Test1 = new OperatorsTestClass69(); OperatorsTestClass69 Test2 = new OperatorsTestClass69(); if (Test1 && Test2) { if ((Test1.intI == 4) && (Test2.intI == 2)) { return true; } else { return false; } } return false; } } class OperatorsTestClass88 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true & true) != true) retVal = false; if ((true & retTrue()) != true) retVal = false; if ((retTrue() & true) != true) retVal = false; if ((true & false) != false) retVal = false; if ((retTrue() & false) != false) retVal = false; if ((true & retFalse()) != false) retVal = false; if ((false & true) != false) retVal = false; if ((retFalse() & true) != false) retVal = false; if ((false & retTrue()) != false) retVal = false; if ((false & false) != false) retVal = false; if ((retFalse() & false) != false) retVal = false; if ((false & retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass89 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true && true) != true) retVal = false; if ((true && retTrue()) != true) retVal = false; if ((retTrue() && true) != true) retVal = false; if ((true && false) != false) retVal = false; if ((retTrue() && false) != false) retVal = false; if ((true && retFalse()) != false) retVal = false; if ((false && true) != false) retVal = false; if ((retFalse() && true) != false) retVal = false; if ((false && retTrue()) != false) retVal = false; if ((false && false) != false) retVal = false; if ((retFalse() && false) != false) retVal = false; if ((false && retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass90 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true | true) != true) retVal = false; if ((true | retTrue()) != true) retVal = false; if ((retTrue() | true) != true) retVal = false; if ((true | false) != true) retVal = false; if ((retTrue() | false) != true) retVal = false; if ((true | retFalse()) != true) retVal = false; if ((false | true) != true) retVal = false; if ((retFalse() | true) != true) retVal = false; if ((false | retTrue()) != true) retVal = false; if ((false | false) != false) retVal = false; if ((retFalse() | false) != false) retVal = false; if ((false | retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass91 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true || true) != true) retVal = false; if ((true || retTrue()) != true) retVal = false; if ((retTrue() || true) != true) retVal = false; if ((true || false) != true) retVal = false; if ((retTrue() || false) != true) retVal = false; if ((true || retFalse()) != true) retVal = false; if ((false || true) != true) retVal = false; if ((retFalse() || true) != true) retVal = false; if ((false || retTrue()) != true) retVal = false; if ((false || false) != false) retVal = false; if ((retFalse() || false) != false) retVal = false; if ((false || retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass92 { public static bool retTrue() { return true; } public static bool retFalse() { return false; } public static bool testMethod() { bool retVal = true; if ((true ^ true) != false) retVal = false; if ((true ^ retTrue()) != false) retVal = false; if ((retTrue() ^ true) != false) retVal = false; if ((true ^ false) != true) retVal = false; if ((retTrue() ^ false) != true) retVal = false; if ((true ^ retFalse()) != true) retVal = false; if ((false ^ true) != true) retVal = false; if ((retFalse() ^ true) != true) retVal = false; if ((false ^ retTrue()) != true) retVal = false; if ((false ^ false) != false) retVal = false; if ((retFalse() ^ false) != false) retVal = false; if ((false ^ retFalse()) != false) retVal = false; return retVal; } } class OperatorsTestClass93 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb + 0) != sb) retVal = false; if ((0 + sb) != sb) retVal = false; if ((b + 0) != b) retVal = false; if ((0 + b) != b) retVal = false; if ((s + 0) != s) retVal = false; if ((0 + s) != s) retVal = false; if ((us + 0) != us) retVal = false; if ((0 + us) != us) retVal = false; if ((i + 0) != i) retVal = false; if ((0 + i) != i) retVal = false; if ((ui + 0) != ui) retVal = false; if ((0 + ui) != ui) retVal = false; if ((l + 0) != l) retVal = false; if ((0 + l) != l) retVal = false; if ((ul + 0) != ul) retVal = false; if ((0 + ul) != ul) retVal = false; return retVal; } } class OperatorsTestClass94 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb - 0) != sb) retVal = false; if ((b - 0) != b) retVal = false; if ((0 - b) != -b) retVal = false; if ((s - 0) != s) retVal = false; if ((0 - s) != -s) retVal = false; if ((us - 0) != us) retVal = false; if ((i - 0) != i) retVal = false; if ((0 - i) != -i) retVal = false; if ((ui - 0) != ui) retVal = false; if ((l - 0) != l) retVal = false; if ((0 - l) != -l) retVal = false; if ((ul - 0) != ul) retVal = false; return retVal; } } class OperatorsTestClass95 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((sb * 0) != 0) retVal = false; if ((0 * sb) != 0) retVal = false; if ((b * 0) != 0) retVal = false; if ((0 * b) != 0) retVal = false; if ((s * 0) != 0) retVal = false; if ((0 * s) != 0) retVal = false; if ((us * 0) != 0) retVal = false; if ((0 * us) != 0) retVal = false; if ((i * 0) != 0) retVal = false; if ((0 * i) != 0) retVal = false; if ((ui * 0) != 0) retVal = false; if ((0 * ui) != 0) retVal = false; if ((l * 0) != 0) retVal = false; if ((0 * l) != 0) retVal = false; if ((ul * 0) != 0) retVal = false; if ((0 * ul) != 0) retVal = false; return retVal; } } class OperatorsTestClass96 { public static bool testMethod() { bool retVal = true; sbyte sb = 2; byte b = 2; short s = 2; ushort us = 2; int i = 2; uint ui = 2; long l = 2; ulong ul = 2; if ((0 / sb) != 0) retVal = false; if ((0 / b) != 0) retVal = false; if ((0 / s) != 0) retVal = false; if ((0 / us) != 0) retVal = false; if ((0 / i) != 0) retVal = false; if ((0 / ui) != 0) retVal = false; if ((0 / l) != 0) retVal = false; if ((0 / ul) != 0) retVal = false; return retVal; } } } }
// The MIT License // // Copyright (c) 2012-2015 Jordan E. Terrell // // 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.Text; using System.Xml; using iSynaptic.Commons.AOP; namespace iSynaptic.Commons.Xml { public abstract class DeclarativeXmlParser { private readonly ParseContext _Context = null; protected DeclarativeXmlParser(XmlReader reader) { Guard.NotNull(reader, "reader"); _Context = new ParseContext(reader); } #region Nested Types protected interface IUponBuilder : IFluentInterface { IAttributeOptions Attribute<T>(string name, Action<T> action); IElementOptions ContentElement<T>(string name, Action<T> action); IElementOptions Element(string name, Action action); void IgnoreUnrecognizedAttributes(); void IgnoreUnrecognizedElements(); void IgnoreUnrecognizedText(); } protected interface IAttributeOptions : IFluentInterface { IAttributeOptions Optional(); } protected interface IElementOptions : IFluentInterface { IElementOptions Empty(); IElementOptions ZeroOrOne(); IElementOptions ZeroOrMore(); IElementOptions OneOrMore(); } protected class UponBuilder : IUponBuilder { private List<IMatcher> _Matchers = null; private readonly XmlToken _Parent = default(XmlToken); private bool _IgnoreUnrecognizedAttributes = false; private bool _IgnoreUnrecognizedElements = false; private bool _IgnoreUnrecognizedText = false; public UponBuilder(XmlToken parent) { _Parent = parent; } public void IgnoreUnrecognizedAttributes() { _IgnoreUnrecognizedAttributes = true; } public void IgnoreUnrecognizedElements() { _IgnoreUnrecognizedElements = true; } public void IgnoreUnrecognizedText() { _IgnoreUnrecognizedText = true; } public IAttributeOptions Attribute<T>(string name, Action<T> action) { var matcher = new Matcher<T>(_Parent, name, XmlNodeType.Attribute, pc => new Maybe<T>(Convert<string, T>.From(pc.Token.Value)), action); Matchers.Add(matcher); return matcher; } public IElementOptions ContentElement<T>(string name, Action<T> action) { Func<ParseContext, Maybe<T>> converter = pc => { var token = pc.Token; if (pc.Token.IsEmptyElement) { pc.Panic(); string message = string.Format("Content element '{0}' must contain text.", name); pc.Errors.Add(new ParseError(message, token)); return Maybe<T>.NoValue; } pc.MoveNext(); if (pc.Token.Kind != XmlNodeType.Text) { pc.Panic(); string message = string.Format("Content element '{0}' must only contain text.", name); pc.Errors.Add(new ParseError(message, token)); return Maybe<T>.NoValue; } var data = Convert<string, T>.From(pc.Token.Value); pc.MoveNext(); if (pc.Token.Kind != XmlNodeType.EndElement) { pc.Panic(); string message = string.Format("Content element '{0}' must only contain text.", name); pc.Errors.Add(new ParseError(message, token)); return Maybe<T>.NoValue; } return new Maybe<T>(data); }; var matcher = new Matcher<T>(_Parent, name, XmlNodeType.Element, converter, action); Matchers.Add(matcher); return matcher; } public IElementOptions Element(string name, Action action) { var matcher = new Matcher<string>(_Parent, name, XmlNodeType.Element, pc => pc.Token.Name.ToMaybe(), x => action()); Matchers.Add(matcher); return matcher; } public void ExecuteMatch(ParseContext pc) { var matcher = Matchers.FirstOrDefault(x => x.CanExecute(pc)); if (matcher == null) { if (pc.Token.Kind == XmlNodeType.Attribute) { if (!_IgnoreUnrecognizedAttributes) pc.Errors.Add(new ParseError(string.Format("Unexpected attribute: '{0}'.", pc.Token.Name), pc.Token)); } else if (pc.Token.Kind == XmlNodeType.Text) { if (!_IgnoreUnrecognizedText) pc.Errors.Add(new ParseError(string.Format("Unexpected text: '{0}'.", pc.Token.Value), pc.Token)); } else if (pc.Token.Kind == XmlNodeType.Element) { if (!_IgnoreUnrecognizedElements) pc.Errors.Add(new ParseError(string.Format("Unexpected element: '{0}'.", pc.Token.Name), pc.Token)); pc.Panic(); } } else matcher.Execute(pc); pc.MoveNext(); } public void ValidateMatchers(ParseContext pc) { foreach (var matcher in Matchers) matcher.ValidateMatcher(pc); } private List<IMatcher> Matchers { get { return _Matchers ?? (_Matchers = new List<IMatcher>()); } } } protected enum Multiplicity { One, ZeroOrOne, ZeroOrMore, OneOrMore } protected interface IMatcher { bool CanExecute(ParseContext context); void Execute(ParseContext context); void ValidateMatcher(ParseContext context); } protected class Matcher<T> : IMatcher, IElementOptions, IAttributeOptions { private readonly XmlToken _Parent; private readonly string _Name; private readonly XmlNodeType _NodeType; private readonly Func<ParseContext, Maybe<T>> _Selector; private readonly Action<T> _MatchAction; private bool _CanBeEmpty = false; private Multiplicity _Multiplicity = Multiplicity.One; private int _ExecutionCount = 0; public Matcher(XmlToken parent, string name, XmlNodeType nodeType, Func<ParseContext, Maybe<T>> selector, Action<T> matchAction) { _Parent = parent; _Name = name; _NodeType = nodeType; _Selector = selector; _MatchAction = matchAction; } IAttributeOptions IAttributeOptions.Optional() { _Multiplicity = Multiplicity.ZeroOrOne; return this; } IElementOptions IElementOptions.Empty() { _CanBeEmpty = true; return this; } IElementOptions IElementOptions.ZeroOrOne() { _Multiplicity = Multiplicity.ZeroOrOne; return this; } IElementOptions IElementOptions.ZeroOrMore() { _Multiplicity = Multiplicity.ZeroOrMore; return this; } IElementOptions IElementOptions.OneOrMore() { _Multiplicity = Multiplicity.OneOrMore; return this; } bool IMatcher.CanExecute(ParseContext context) { return context.Token.Name == _Name && context.Token.Kind == _NodeType; } void IMatcher.Execute(ParseContext context) { _ExecutionCount++; bool shouldExecuteAtMostOnce = _Multiplicity == Multiplicity.One || _Multiplicity == Multiplicity.ZeroOrOne; if (shouldExecuteAtMostOnce && _ExecutionCount > 1) { var token = context.Token; _Selector(context); string nodeType = _NodeType == XmlNodeType.Text ? "text node" : _NodeType.ToString().ToLower(); string message = string.Format("More than one '{0}' {1} is not allowed.", _Name, nodeType); context.Errors.Add(new ParseError(message, token)); } else if (context.Token.IsEmptyElement && _CanBeEmpty) { context.Panic(); } else { _Selector(context) .OnValue(x => _MatchAction(x)) .Suppress(x => context.Errors.Add(new ParseError(string.Format("Unable to interpet data; exception occured: {0}", x.Message), context.Token))) .Run(); } } void IMatcher.ValidateMatcher(ParseContext context) { bool required = _Multiplicity == Multiplicity.One || _Multiplicity == Multiplicity.OneOrMore; if (required && _ExecutionCount <= 0) { string nodeType = _NodeType == XmlNodeType.Text ? "text node" : _NodeType.ToString().ToLower(); string message = string.Format("At least one '{0}' {1} is required.", _Name, nodeType); context.Errors.Add(new ParseError(message, _Parent)); } } } protected class ParseContext { public ParseContext(XmlReader reader) { Guard.NotNull(reader, "reader"); Tokens = ParseElement(reader).GetEnumerator(); Token = XmlToken.None; Errors = new List<ParseError>(); } private static IEnumerable<XmlToken> ParseElement(XmlReader reader) { if (reader.NodeType == XmlNodeType.None && reader.EOF != true) reader.Read(); yield return XmlToken.FromReader(reader); bool isEmptyElement = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) yield return XmlToken.FromReader(reader); } if (isEmptyElement != true) { while (ReadPastWhiteSpace(reader)) { if (reader.NodeType == XmlNodeType.EndElement) { yield return XmlToken.FromReader(reader); break; } if (reader.NodeType == XmlNodeType.Text) yield return XmlToken.FromReader(reader); if (reader.NodeType == XmlNodeType.Element) { foreach (var token in ParseElement(reader)) yield return token; } } } else yield return XmlToken.EndElement; } private static bool ReadPastWhiteSpace(XmlReader reader) { bool results = false; do { results = reader.Read(); } while (reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace); return results; } public bool MoveNext() { bool results = Tokens.MoveNext(); Token = Tokens.Current; return results; } public void Panic() { MoveNext(); int expectedEndElements = 0; while (Token.Kind != XmlNodeType.EndElement || expectedEndElements > 0) { if (Token.Kind == XmlNodeType.Element) expectedEndElements++; if (Token.Kind == XmlNodeType.EndElement) expectedEndElements--; MoveNext(); } } public XmlToken Token { get; private set; } public List<ParseError> Errors { get; private set; } private IEnumerator<XmlToken> Tokens { get; set; } } public class ParseError { public ParseError(string message, XmlToken token) { Message = message; Token = token; } public string Message { get; private set; } public XmlToken Token { get; private set; } } protected ParseContext Context { get { return _Context; } } #endregion protected IEnumerable<ParseError> Upon(Action<IUponBuilder> builderActions) { if (Context.Token.Kind == XmlNodeType.None) Context.MoveNext(); if (Context.Token.Kind != XmlNodeType.Element) throw new InvalidOperationException("Upon can only be called while reader's current node is the start of an element"); var builder = new UponBuilder(Context.Token); builderActions(builder); Context.MoveNext(); while (Context.Token.Kind != XmlNodeType.EndElement) builder.ExecuteMatch(Context); builder.ValidateMatchers(Context); return Context.Errors; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Diagnostics; using System.Text; using System.Windows.Forms; using Dw.Window; using Native.Monitor; using Native.Desktop; using Fs.IO; using Fs; using System.IO; using Fs.Reflection; namespace Dw { public partial class MainForm : PluginForm { public delegate void OnMainFormLoadedDelegate(); public OnMainFormLoadedDelegate OnMainFormLoaded; public bool AllowClose = false; internal string BgImgDir { get { return _bgImgDir; } set { string baseDir = AppDomain.CurrentDomain.BaseDirectory; if (baseDir[baseDir.Length - 1] != '\\') { baseDir += '\\'; } if (string.IsNullOrEmpty(value)) { _bgImgDir = baseDir; return; } if (value.IndexOf(':') >= 1) { _bgImgDir = value; } else { _bgImgDir = baseDir + value; } if (!Directory.Exists(_bgImgDir)) { _bgImgDir = baseDir + "BgImg"; Bitmap bi = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics g = Graphics.FromImage(bi); g.FillRectangle(Brushes.Black, 0, 0, Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); g.Dispose(); bi.Save(_bgImgDir + "\\_default.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); bi.Dispose(); } ClassHelper.CreateThread(delegate(object par) { bool rlt = DiskHelper.EnumDirectory(_bgImgDir, delegate(string path, DiskHelper.DirectoryItemType type) { if (type == DiskHelper.DirectoryItemType.File) { try { FileInfo fi = new FileInfo(path); if (fi.Extension != "ini" && fi.Extension != "db") { Bitmap bi = new Bitmap(path); bgs.Add(path); } } catch (Exception err) { Exceptions.LogOnly(err); } } return true; }); }); } }protected string _bgImgDir; protected List<string> bgs = new List<string>(); protected Random rnd = new Random(); protected System.Timers.Timer tmr; public MainForm() : base() { InitializeComponent(); Dispose += Dispose_Delegate; int scrHeight, scrWidth; Left = 0; Top = 0; FormBorderStyle = FormBorderStyle.None; WindowState = FormWindowState.Normal; scrHeight = Screen.PrimaryScreen.Bounds.Height; //System.Windows.SystemParameters.PrimaryScreenHeight; scrWidth = Screen.PrimaryScreen.Bounds.Width; //System.Windows.SystemParameters.PrimaryScreenWidth; Width = scrWidth; Height = scrHeight; tmr = new System.Timers.Timer(); tmr.Interval = 399; tmr.Enabled = true; tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed); tmr.Start(); Opacity = 0; ShowInTaskbar = false; MsgFilter.OnMsgProcess += new MsgFilter.MsgProcessDelegate(delegate(ref Message m) { switch (m.Msg) { //WM_QUERYENDSESSION case (0x0011): m.Result = IntPtr.Zero; return true; //WM_SYSCOMAND SC_SCREENSAVE SC_MONITORPOWER case (0x0112): if (m.LParam == (IntPtr)0xF140 || m.LParam == (IntPtr)0XF170) { m.Result = IntPtr.Zero; return true; } else { return false; } default: return false; } }); MsgFilter.Start(); } public void HideScreen() { TopMost = false; Opacity = 0; Hide(); } public void UnlockScreen() { if (TopMost) { TopMost = false; SendKeys.SendWait("%{Tab}"); Taskbar.AdjustSizeAgainstTaskBar(this); } } public void LockScreen() { if (Opacity <= 0) { if (bgs.Count >= 1) { SwitchImage(); } Opacity = 1; } //BgPic.SizeMode = PictureBoxSizeMode.StretchImage; Width = Screen.PrimaryScreen.Bounds.Width; Height = Screen.PrimaryScreen.Bounds.Height; ShowInTaskbar = false; TopMost = true; Show(); } public void SwitchImage() { Bitmap bi = null; if (BgPic != null && BgPic.Image != null) { bi = new Bitmap(BgPic.Image); } BgPic.Image = GetRandomImg(); if (bi != null) { bi.Dispose(); } } Bitmap GetRandomImg() { Bitmap rlt = null; int index; if (bgs.Count > 0) { for (int i = 1; i <= 10; i++) { index = rnd.Next(1, bgs.Count + 1) - 1; try { rlt = new Bitmap(bgs[index]); break; } catch (Exception err) { Exceptions.LogOnly(err); } } } return rlt; } void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Screensaver.KillScreenSaver(false); if (TopMost) { Invoke((MethodInvoker)delegate() { Activate(); }); } } protected override void OnLoad(EventArgs e) { if (bgs.Count > 0) { BgPic.Image = GetRandomImg(); } if (OnMainFormLoaded != null) { OnMainFormLoaded(); } } protected override void OnClosing(CancelEventArgs e) { if (AllowClose) { return; } else { e.Cancel = true; } } } }
// // System.Net.HttpConnection // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Net.Sockets; using System.Reflection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using HTTP.Net; namespace HTTP.Net { internal class HttpConnection { private static AsyncCallback onread_cb = new AsyncCallback(OnRead); private const int BufferSize = 8192; private Socket sock; private Stream stream; private EndPointListener epl; private MemoryStream ms; private byte[] buffer; private StringBuilder current_line; private ListenerPrefix prefix; private RequestStream i_stream; private ResponseStream o_stream; private bool chunked; private int reuses; private bool context_bound; private bool secure; private AsymmetricAlgorithm key; private int s_timeout = 90000; // 90k ms for first request, 15k ms from then on private Timer timer; private IPEndPoint local_ep; private MonoContext context; private HttpListen last_listener; public HttpConnection(Socket sock, EndPointListener epl, bool secure, X509Certificate2 cert, AsymmetricAlgorithm key) { this.sock = sock; this.epl = epl; this.secure = secure; this.key = key; if (secure == false) { stream = new NetworkStream (sock, false); } else { //SslServerStream ssl_stream = new SslServerStream (new NetworkStream (sock, false), cert, false, false); //ssl_stream.PrivateKeyCertSelectionDelegate += OnPVKSelection; //stream = ssl_stream; } timer = new Timer (OnTimeout, null, Timeout.Infinite, Timeout.Infinite); Init (); } AsymmetricAlgorithm OnPVKSelection (X509Certificate certificate, string targetHost) { return key; } void Init() { context_bound = false; i_stream = null; o_stream = null; prefix = null; chunked = false; ms = new MemoryStream (); position = 0; input_state = InputState.RequestLine; line_state = LineState.None; context = new MonoContext(this); } public bool IsClosed { get { return (sock == null); } } public int Reuses { get { return reuses; } } public IPEndPoint LocalEndPoint { get { if (local_ep != null) return local_ep; local_ep = (IPEndPoint) sock.LocalEndPoint; return local_ep; } } public IPEndPoint RemoteEndPoint { get { return (IPEndPoint) sock.RemoteEndPoint; } } public bool IsSecure { get { return secure; } } public ListenerPrefix Prefix { get { return prefix; } set { prefix = value; } } void OnTimeout (object unused) { CloseSocket (); Unbind (); } public void BeginReadRequest () { if (buffer == null) buffer = new byte [BufferSize]; try { if (reuses == 1) s_timeout = 15000; timer.Change (s_timeout, Timeout.Infinite); stream.BeginRead (buffer, 0, BufferSize, onread_cb, this); } catch { timer.Change (Timeout.Infinite, Timeout.Infinite); CloseSocket (); Unbind (); } } public RequestStream GetRequestStream (bool chunked, long contentlength) { if (i_stream == null) { byte [] buffer = ms.GetBuffer (); int length = (int) ms.Length; ms = null; if (chunked) { this.chunked = true; context.Response.SendChunked = true; i_stream = new ChunkedInputStream (context, stream, buffer, position, length - position); } else { i_stream = new RequestStream (stream, buffer, position, length - position, contentlength); } } return i_stream; } public ResponseStream GetResponseStream () { // TODO: can we get this stream before reading the input? if (o_stream == null) { HttpListen listener = context.Listener; bool ign = (listener == null) ? true : listener.IgnoreWriteExceptions; o_stream = new ResponseStream (stream, context.iResponse, ign); } return o_stream; } static void OnRead (IAsyncResult ares) { HttpConnection cnc = (HttpConnection) ares.AsyncState; cnc.OnReadInternal (ares); } void OnReadInternal (IAsyncResult ares) { timer.Change (Timeout.Infinite, Timeout.Infinite); int nread = -1; try { nread = stream.EndRead (ares); ms.Write (buffer, 0, nread); if (ms.Length > 32768) { SendError ("Bad request", 400); Close (true); return; } } catch { if (ms != null && ms.Length > 0) SendError (); if (sock != null) { CloseSocket (); Unbind (); } return; } if (nread == 0) { //if (ms.Length > 0) // SendError (); // Why bother? CloseSocket (); Unbind (); return; } if (ProcessInput (ms)) { if (!context.HaveError) context.iRequest.FinishInitialization (); if (context.HaveError) { SendError (); Close (true); return; } if (!epl.BindContext (context)) { SendError ("Invalid host", 400); Close (true); return; } HttpListen listener = context.Listener; if (last_listener != listener) { RemoveConnection (); listener.AddConnection (this); last_listener = listener; } context_bound = true; listener.RegisterContext (context); return; } stream.BeginRead (buffer, 0, BufferSize, onread_cb, this); } void RemoveConnection () { if (last_listener == null) epl.RemoveConnection (this); else last_listener.RemoveConnection (this); } enum InputState { RequestLine, Headers } enum LineState { None, CR, LF } InputState input_state = InputState.RequestLine; LineState line_state = LineState.None; int position; // true -> done processing // false -> need more input bool ProcessInput (MemoryStream ms) { byte [] buffer = ms.GetBuffer (); int len = (int) ms.Length; int used = 0; string line; try { line = ReadLine (buffer, position, len - position, ref used); position += used; } catch { context.ErrorMessage = "Bad request"; context.ErrorStatus = 400; return true; } do { if (line == null) break; if (line == "") { if (input_state == InputState.RequestLine) continue; current_line = null; ms = null; return true; } if (input_state == InputState.RequestLine) { context.iRequest.SetRequestLine(line); input_state = InputState.Headers; } else { try { context.iRequest.AddHeader (line); } catch (Exception e) { context.ErrorMessage = e.Message; context.ErrorStatus = 400; return true; } } if (context.HaveError) return true; if (position >= len) break; try { line = ReadLine (buffer, position, len - position, ref used); position += used; } catch { context.ErrorMessage = "Bad request"; context.ErrorStatus = 400; return true; } } while (line != null); if (used == len) { ms.SetLength (0); position = 0; } return false; } string ReadLine (byte [] buffer, int offset, int len, ref int used) { if (current_line == null) current_line = new StringBuilder (128); int last = offset + len; used = 0; for (int i = offset; i < last && line_state != LineState.LF; i++) { used++; byte b = buffer [i]; if (b == 13) { line_state = LineState.CR; } else if (b == 10) { line_state = LineState.LF; } else { current_line.Append ((char) b); } } string result = null; if (line_state == LineState.LF) { line_state = LineState.None; result = current_line.ToString (); current_line.Length = 0; } return result; } public void SendError (string msg, int status) { try { HttpListenerResponse response = context.iResponse; response.StatusCode = status; response.ContentType = "text/html"; string description = HttpListenerResponse.GetStatusDescription (status); string str; if (msg != null) str = String.Format ("<h1>{0} ({1})</h1>", description, msg); else str = String.Format ("<h1>{0}</h1>", description); byte [] error = context.Response.ContentEncoding.GetBytes (str); response.Close (error, false); } catch { // response was already closed } } public void SendError () { SendError (context.ErrorMessage, context.ErrorStatus); } void Unbind () { if (context_bound) { epl.UnbindContext (context); context_bound = false; } } public void Close () { Close (false); } void CloseSocket () { if (sock == null) return; try { sock.Close (); } catch { } finally { sock = null; } RemoveConnection (); } internal void Close (bool force_close) { if (sock != null) { Stream st = GetResponseStream (); st.Close (); o_stream = null; } if (sock != null) { force_close |= !context.Request.KeepAlive; if (!force_close) force_close = (context.Response.Headers ["connection"] == "close"); /* if (!force_close) { // bool conn_close = (status_code == 400 || status_code == 408 || status_code == 411 || // status_code == 413 || status_code == 414 || status_code == 500 || // status_code == 503); force_close |= (context.Request.ProtocolVersion <= HttpVersion.Version10); } */ if (!force_close && context.iRequest.FlushInput ()) { if (chunked && context.iResponse.ForceCloseChunked == false) { // Don't close. Keep working. reuses++; Unbind (); Init (); BeginReadRequest (); return; } reuses++; Unbind (); Init (); BeginReadRequest (); return; } Socket s = sock; sock = null; try { if (s != null) s.Shutdown (SocketShutdown.Both); } catch { } finally { if (s != null) s.Close (); } Unbind (); RemoveConnection (); return; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SAEON.Observations.Data { /// <summary> /// Strongly-typed collection for the AspnetUsersInRole class. /// </summary> [Serializable] public partial class AspnetUsersInRoleCollection : ActiveList<AspnetUsersInRole, AspnetUsersInRoleCollection> { public AspnetUsersInRoleCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AspnetUsersInRoleCollection</returns> public AspnetUsersInRoleCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AspnetUsersInRole o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the aspnet_UsersInRoles table. /// </summary> [Serializable] public partial class AspnetUsersInRole : ActiveRecord<AspnetUsersInRole>, IActiveRecord { #region .ctors and Default Settings public AspnetUsersInRole() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AspnetUsersInRole(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AspnetUsersInRole(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AspnetUsersInRole(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("aspnet_UsersInRoles", TableType.Table, DataService.GetInstance("ObservationsDB")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarUserId = new TableSchema.TableColumn(schema); colvarUserId.ColumnName = "UserId"; colvarUserId.DataType = DbType.Guid; colvarUserId.MaxLength = 0; colvarUserId.AutoIncrement = false; colvarUserId.IsNullable = false; colvarUserId.IsPrimaryKey = true; colvarUserId.IsForeignKey = true; colvarUserId.IsReadOnly = false; colvarUserId.DefaultSetting = @""; colvarUserId.ForeignKeyTableName = "aspnet_Users"; schema.Columns.Add(colvarUserId); TableSchema.TableColumn colvarRoleId = new TableSchema.TableColumn(schema); colvarRoleId.ColumnName = "RoleId"; colvarRoleId.DataType = DbType.Guid; colvarRoleId.MaxLength = 0; colvarRoleId.AutoIncrement = false; colvarRoleId.IsNullable = false; colvarRoleId.IsPrimaryKey = true; colvarRoleId.IsForeignKey = true; colvarRoleId.IsReadOnly = false; colvarRoleId.DefaultSetting = @""; colvarRoleId.ForeignKeyTableName = "aspnet_Roles"; schema.Columns.Add(colvarRoleId); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["ObservationsDB"].AddSchema("aspnet_UsersInRoles",schema); } } #endregion #region Props [XmlAttribute("UserId")] [Bindable(true)] public Guid UserId { get { return GetColumnValue<Guid>(Columns.UserId); } set { SetColumnValue(Columns.UserId, value); } } [XmlAttribute("RoleId")] [Bindable(true)] public Guid RoleId { get { return GetColumnValue<Guid>(Columns.RoleId); } set { SetColumnValue(Columns.RoleId, value); } } #endregion #region ForeignKey Properties private SAEON.Observations.Data.AspnetRole _AspnetRole = null; /// <summary> /// Returns a AspnetRole ActiveRecord object related to this AspnetUsersInRole /// /// </summary> public SAEON.Observations.Data.AspnetRole AspnetRole { // get { return SAEON.Observations.Data.AspnetRole.FetchByID(this.RoleId); } get { return _AspnetRole ?? (_AspnetRole = SAEON.Observations.Data.AspnetRole.FetchByID(this.RoleId)); } set { SetColumnValue("RoleId", value.RoleId); } } private SAEON.Observations.Data.AspnetUser _AspnetUser = null; /// <summary> /// Returns a AspnetUser ActiveRecord object related to this AspnetUsersInRole /// /// </summary> public SAEON.Observations.Data.AspnetUser AspnetUser { // get { return SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId); } get { return _AspnetUser ?? (_AspnetUser = SAEON.Observations.Data.AspnetUser.FetchByID(this.UserId)); } set { SetColumnValue("UserId", value.UserId); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(Guid varUserId,Guid varRoleId) { AspnetUsersInRole item = new AspnetUsersInRole(); item.UserId = varUserId; item.RoleId = varRoleId; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(Guid varUserId,Guid varRoleId) { AspnetUsersInRole item = new AspnetUsersInRole(); item.UserId = varUserId; item.RoleId = varRoleId; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn UserIdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn RoleIdColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string UserId = @"UserId"; public static string RoleId = @"RoleId"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Drawing; using System.IO; namespace Imageflow.Fluent { public class BuildNode :BuildItemBase { internal static BuildNode StartNode(ImageJob graph, object data) => new BuildNode(graph, data, null, null); /// <summary> /// Encode the result to the given destination (such as a BytesDestination or StreamDestination) /// </summary> /// <param name="destination">Where to write the bytes</param> /// <param name="ioId"></param> /// <param name="encoderPreset">An encoder class, such as `new MozJpegEncoder()`</param> /// <returns></returns> public BuildEndpoint Encode(IOutputDestination destination, int ioId, IEncoderPreset encoderPreset) { Builder.AddOutput(ioId, destination); return new BuildEndpoint(Builder, new {encode = new {io_id = ioId, preset = encoderPreset?.ToImageflowDynamic()}}, this, null); } /// <summary> /// Encode the result to the given destination (such as a BytesDestination or StreamDestination) /// </summary> /// <param name="destination">Where to write the bytes</param> /// <param name="encoderPreset">An encoder class, such as `new MozJpegEncoder()`</param> /// <returns></returns> public BuildEndpoint Encode(IOutputDestination destination, IEncoderPreset encoderPreset) => Encode( destination, Builder.GenerateIoId(), encoderPreset); [Obsolete("Use Encode(IOutputDestination destination, int ioId, IEncoderPreset encoderPreset)")] public BuildEndpoint EncodeToBytes(int ioId, IEncoderPreset encoderPreset) => Encode(new BytesDestination(), ioId, encoderPreset); public BuildEndpoint EncodeToBytes(IEncoderPreset encoderPreset) => Encode(new BytesDestination(), encoderPreset); [Obsolete("Use Encode(IOutputDestination destination, int ioId, IEncoderPreset encoderPreset)")] public BuildEndpoint EncodeToStream(Stream stream, bool disposeStream, int ioId, IEncoderPreset encoderPreset) => Encode(new StreamDestination(stream, disposeStream), ioId, encoderPreset); public BuildEndpoint EncodeToStream(Stream stream, bool disposeStream, IEncoderPreset encoderPreset) => Encode(new StreamDestination(stream, disposeStream), encoderPreset); private BuildNode(ImageJob builder,object nodeData, BuildNode inputNode, BuildNode canvasNode) : base(builder, nodeData, inputNode, canvasNode){} private BuildNode To(object data) => new BuildNode(Builder, data, this, null); private BuildNode NodeWithCanvas(BuildNode canvas, object data) => new BuildNode(Builder, data, this, canvas); /// <summary> /// Downscale the image to fit within the given dimensions, but do not upscale. See Constrain() for more options. /// </summary> /// <param name="w"></param> /// <param name="h"></param> /// <returns></returns> public BuildNode ConstrainWithin(uint? w, uint? h) => To(new { constrain = new {mode="within", w, h } }); /// <summary> /// Downscale the image to fit within the given dimensions, but do not upscale. See Constrain() for more options. /// </summary> /// <param name="w"></param> /// <param name="h"></param> /// <param name="hints"></param> /// <returns></returns> public BuildNode ConstrainWithin(uint? w, uint? h, ResampleHints hints) => To(new { constrain = new { mode = "within", w, h, hints = hints?.ToImageflowDynamic() } }); /// <summary> /// Scale an image using the given Constraint object. /// </summary> /// <param name="constraint"></param> /// <returns></returns> public BuildNode Constrain(Constraint constraint) => To(new { constrain = constraint.ToImageflowDynamic() }); /// <summary> /// Distort the image to exactly the given dimensions. /// </summary> /// <param name="w"></param> /// <param name="h"></param> /// <returns></returns> public BuildNode Distort(uint w, uint h) => Distort(w, h, null); /// <summary> /// Distort the image to exactly the given dimensions. /// </summary> /// <param name="w"></param> /// <param name="h"></param> /// <param name="hints"></param> /// <returns></returns> public BuildNode Distort(uint w, uint h, ResampleHints hints) => To(new { resample_2d = new { w, h, hints = hints?.ToImageflowDynamic() } }); /// <summary> /// Crops the image to the given coordinates /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <returns></returns> public BuildNode Crop(int x1, int y1, int x2, int y2) => To(new { crop = new { x1, y1, x2, y2 } }); /// <summary> /// Region is like a crop command, but you can specify coordinates outside of the image and /// thereby add padding. It's like a window. Coordinates are in pixels. /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <param name="backgroundColor"></param> /// <returns></returns> public BuildNode Region(int x1, int y1, int x2, int y2, AnyColor backgroundColor) => To(new { region = new { x1, y1, x2, y2, background_color = backgroundColor.ToImageflowDynamic() } }); /// <summary> /// Region is like a crop command, but you can specify coordinates outside of the image and /// thereby add padding. It's like a window. /// You can specify a region as a percentage of the image's width and height. /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <param name="backgroundColor"></param> /// <returns></returns> public BuildNode RegionPercent(float x1, float y1, float x2, float y2, AnyColor backgroundColor) => To(new { region_percent = new { x1, y1, x2, y2, background_color = backgroundColor.ToImageflowDynamic() } }); /// <summary> /// Crops away whitespace of any color at the edges of the image. /// </summary> /// <param name="threshold">(1..255). determines how much noise/edges to tolerate before cropping /// is finalized. 80 is a good starting point.</param> /// <param name="percentPadding">determines how much of the image to restore after cropping to /// provide some padding. 0.5 (half a percent) is a good starting point.</param> /// <returns></returns> public BuildNode CropWhitespace(int threshold, float percentPadding) => To(new { crop_whitespace = new { threshold, percent_padding = percentPadding } }); /// <summary> /// Does not honor encoding or decoding parameters. Use ImageJob.BuildCommandString() instead unless /// you are actually combining this node with others in a job. /// </summary> /// <param name="commandString"></param> /// <returns></returns> public BuildNode ResizerCommands(string commandString) => To(new { command_string = new { kind = "ir4", value = commandString } }); /// <summary> /// Flips the image vertically /// </summary> /// <returns></returns> public BuildNode FlipVertical() => To(new {flip_v = (string)null}); /// <summary> /// Flips the image horizontally /// </summary> /// <returns></returns> public BuildNode FlipHorizontal() => To(new {flip_h = (string)null }); /// <summary> /// Rotates the image 90 degrees clockwise. /// </summary> /// <returns></returns> public BuildNode Rotate90() => To(new {rotate_90 = (string)null }); /// <summary> /// Rotates the image 180 degrees clockwise. /// </summary> /// <returns></returns> public BuildNode Rotate180() => To(new {rotate_180 = (string)null }); /// <summary> /// Rotates the image 270 degrees clockwise. (same as 90 degrees counterclockwise). /// </summary> /// <returns></returns> public BuildNode Rotate270() => To(new {rotate_270 = (string)null }); /// <summary> /// Swaps the x and y dimensions of the image /// </summary> /// <returns></returns> public BuildNode Transpose() => To(new {transpose = (string)null }); /// <summary> /// Allows you to generate multiple outputs by branching the graph /// <code> /// var r = await b.Decode(imageBytes) /// .Branch(f => f.EncodeToBytes(new WebPLosslessEncoder())) /// .Branch(f => f.EncodeToBytes(new WebPLossyEncoder(50))) /// .EncodeToBytes(new LibPngEncoder()) /// .Finish().InProcessAsync(); /// </code> /// </summary> /// <param name="f"></param> /// <returns></returns> public BuildNode Branch(Func<BuildNode, BuildEndpoint> f) { f(this); return this; } /// <summary> /// Copies (not composes) the given rectangle from input to canvas. /// You cannot copy from a BGRA input to a BGR canvas. /// </summary> /// <param name="canvas"></param> /// <param name="area"></param> /// <param name="to"></param> /// <returns></returns> public BuildNode CopyRectTo(BuildNode canvas, Rectangle area, Point to) => NodeWithCanvas(canvas, new { copy_rect_to_canvas = new { from_x = area.X, from_y = area.Y, w = area.Width, h = area.Height, x = to.X, y = to.Y } }); /// <summary> /// Draws the input image to the given rectangle on the canvas, distorting if the aspect ratios differ. /// /// </summary> /// <param name="canvas"></param> /// <param name="to"></param> /// <param name="hints"></param> /// <param name="blend"></param> /// <returns></returns> public BuildNode DrawImageExactTo(BuildNode canvas, Rectangle to, ResampleHints hints, CompositingMode? blend) => NodeWithCanvas(canvas, new { draw_image_exact = new { w = to.Width, h = to.Height, x = to.X, y = to.Y, blend = blend?.ToString()?.ToLowerInvariant(), hints = hints?.ToImageflowDynamic() } }); /// <summary> /// Fills the given rectangle with the specified color /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <param name="color"></param> /// <returns></returns> public BuildNode FillRectangle(int x1, int y1, int x2, int y2, AnyColor color) => To(new { fill_rect = new { x1, y1, x2, y2, color = color.ToImageflowDynamic() } }); /// <summary> /// Adds padding of the given color by enlarging the canvas on the sides specified. /// </summary> /// <param name="left"></param> /// <param name="top"></param> /// <param name="right"></param> /// <param name="bottom"></param> /// <param name="color"></param> /// <returns></returns> public BuildNode ExpandCanvas(int left, int top, int right, int bottom, AnyColor color) => To(new { expand_canvas = new { left, top, right, bottom, color = color.ToImageflowDynamic() } }); /// <summary> /// This command is not endorsed as it operates in the sRGB space and does not produce perfect results. /// </summary> /// <param name="threshold"></param> /// <returns></returns> public BuildNode WhiteBalanceSrgb(int threshold) => To(new { white_balance_histogram_area_threshold_srgb = new { threshold } }); /// <summary> /// Set the transparency of the image from 0 (transparent) to 1 (opaque) /// </summary> /// <param name="opacity"></param> /// <returns></returns> public BuildNode TransparencySrgb(float opacity) => To(new { color_filter_srgb = new { alpha = opacity } }); /// <summary> /// Adjust contrast between -1 and 1. /// </summary> /// <param name="amount">-1...1</param> /// <returns></returns> public BuildNode ContrastSrgb(float amount) => To(new { color_filter_srgb = new { contrast = amount } }); /// <summary> /// Adjust brightness between -1 and 1. /// </summary> /// <param name="amount">-1...1</param> /// <returns></returns> public BuildNode BrightnessSrgb(float amount) => To(new { color_filter_srgb = new { brightness = amount } }); /// <summary> /// Adjust saturation between -1 and 1. /// </summary> /// <param name="amount">-1...1</param> /// <returns></returns> public BuildNode SaturationSrgb(float amount) => To(new { color_filter_srgb = new { saturation = amount } }); /// <summary> /// Apply filters like grayscale, sepia, or inversion in the sRGB color space /// </summary> /// <param name="filter"></param> /// <returns></returns> public BuildNode ColorFilterSrgb(ColorFilterSrgb filter) => To(new { color_filter_srgb = filter.ToString().ToLowerInvariant() }); /// <summary> /// Draw a watermark from the given BytesSource or StreamSource /// </summary> /// <param name="source"></param> /// <param name="watermark"></param> /// <returns></returns> public BuildNode Watermark(IBytesSource source, WatermarkOptions watermark) => Watermark(source, null, watermark); /// <summary> /// Draw a watermark from the given BytesSource or StreamSource /// </summary> /// <param name="source"></param> /// <param name="ioId"></param> /// <param name="watermark"></param> /// <returns></returns> public BuildNode Watermark(IBytesSource source, int? ioId, WatermarkOptions watermark) { if (ioId == null) { ioId = this.Builder.GenerateIoId(); } this.Builder.AddInput(ioId.Value, source); return To(new { watermark = watermark.ToImageflowDynamic(ioId.Value) }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers.Binary; using System.Diagnostics; using System.Text; using Internal.Runtime.CompilerServices; namespace System.Globalization { /// <summary> /// This class implements a set of methods for retrieving character type /// information. Character type information is independent of culture /// and region. /// </summary> public static partial class CharUnicodeInfo { internal const char HIGH_SURROGATE_START = '\ud800'; internal const char HIGH_SURROGATE_END = '\udbff'; internal const char LOW_SURROGATE_START = '\udc00'; internal const char LOW_SURROGATE_END = '\udfff'; internal const int HIGH_SURROGATE_RANGE = 0x3FF; internal const int UNICODE_CATEGORY_OFFSET = 0; internal const int BIDI_CATEGORY_OFFSET = 1; // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff. internal const int UNICODE_PLANE01_START = 0x10000; /// <summary> /// Convert the BMP character or surrogate pointed by index to a UTF32 value. /// This is similar to char.ConvertToUTF32, but the difference is that /// it does not throw exceptions when invalid surrogate characters are passed in. /// /// WARNING: since it doesn't throw an exception it CAN return a value /// in the surrogate range D800-DFFF, which are not legal unicode values. /// </summary> internal static int InternalConvertToUtf32(string s, int index) { Debug.Assert(s != null, "s != null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return (int)s[index]; } internal static int InternalConvertToUtf32(StringBuilder s, int index) { Debug.Assert(s != null, "s != null"); Debug.Assert(index >= 0 && index < s.Length, "index < s.Length"); int c = (int)s[index]; if (index < s.Length - 1) { int temp1 = c - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. return (temp1 * 0x400) + temp2 + UNICODE_PLANE01_START; } } } return c; } /// <summary> /// Convert a character or a surrogate pair starting at index of string s /// to UTF32 value. /// WARNING: since it doesn't throw an exception it CAN return a value /// in the surrogate range D800-DFFF, which are not legal unicode values. /// </summary> internal static int InternalConvertToUtf32(string s, int index, out int charLength) { Debug.Assert(s != null, "s != null"); Debug.Assert(s.Length > 0, "s.Length > 0"); Debug.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length"); charLength = 1; if (index < s.Length - 1) { int temp1 = (int)s[index] - HIGH_SURROGATE_START; if ((uint)temp1 <= HIGH_SURROGATE_RANGE) { int temp2 = (int)s[index + 1] - LOW_SURROGATE_START; if ((uint)temp2 <= HIGH_SURROGATE_RANGE) { // Convert the surrogate to UTF32 and get the result. charLength++; return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START); } } } return ((int)s[index]); } /// <summary> /// This is called by the public char and string, index versions /// Note that for ch in the range D800-DFFF we just treat it as any /// other non-numeric character /// </summary> internal static double InternalGetNumericValue(int ch) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. int index = ch >> 8; if ((uint)index < (uint)NumericLevel1Index.Length) { index = NumericLevel1Index[index]; // Get the level 2 offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = NumericLevel2Index[(index << 4) + ((ch >> 4) & 0x000f)]; index = NumericLevel3Index[(index << 4) + (ch & 0x000f)]; ref var value = ref Unsafe.AsRef(in NumericValues[index * 8]); if (BitConverter.IsLittleEndian) { return Unsafe.ReadUnaligned<double>(ref value); } return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReverseEndianness(Unsafe.ReadUnaligned<long>(ref value))); } return -1; } internal static byte InternalGetDigitValues(int ch, int offset) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 12 bit (8 - 19) of ch. int index = ch >> 8; if ((uint)index < (uint)NumericLevel1Index.Length) { index = NumericLevel1Index[index]; // Get the level 2 offset from the 4 - 7 bit of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = NumericLevel2Index[(index << 4) + ((ch >> 4) & 0x000f)]; index = NumericLevel3Index[(index << 4) + (ch & 0x000f)]; return DigitValues[index * 2 + offset]; } return 0xff; } /// <summary> /// Returns the numeric value associated with the character c. /// If the character is a fraction, the return value will not be an /// integer. If the character does not have a numeric value, the return /// value is -1. /// </summary> public static double GetNumericValue(char ch) { return InternalGetNumericValue(ch); } public static double GetNumericValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return InternalGetNumericValue(InternalConvertToUtf32(s, index)); } public static int GetDecimalDigitValue(char ch) { return (sbyte)InternalGetDigitValues(ch, 0); } public static int GetDecimalDigitValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (sbyte)InternalGetDigitValues(InternalConvertToUtf32(s, index), 0); } public static int GetDigitValue(char ch) { return (sbyte)InternalGetDigitValues(ch, 1); } public static int GetDigitValue(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index); } return (sbyte)InternalGetDigitValues(InternalConvertToUtf32(s, index), 1); } public static UnicodeCategory GetUnicodeCategory(char ch) { return GetUnicodeCategory((int)ch); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return InternalGetUnicodeCategory(s, index); } public static UnicodeCategory GetUnicodeCategory(int codePoint) { return (UnicodeCategory)InternalGetCategoryValue(codePoint, UNICODE_CATEGORY_OFFSET); } /// <summary> /// Returns the Unicode Category property for the character c. /// Note that this API will return values for D800-DF00 surrogate halves. /// </summary> internal static byte InternalGetCategoryValue(int ch, int offset) { Debug.Assert(ch >= 0 && ch <= 0x10ffff, "ch is not in valid Unicode range."); // Get the level 2 item from the highest 11 bits of ch. int index = CategoryLevel1Index[ch >> 9]; // Get the level 2 WORD offset from the next 5 bits of ch. This provides the base offset of the level 3 table. // Note that & has the lower precedence than addition, so don't forget the parathesis. index = Unsafe.ReadUnaligned<ushort>(ref Unsafe.AsRef(in CategoryLevel2Index[(index << 6) + ((ch >> 3) & 0b111110)])); if (!BitConverter.IsLittleEndian) { index = BinaryPrimitives.ReverseEndianness((ushort)index); } // Get the result from the 0 -3 bit of ch. index = CategoryLevel3Index[(index << 4) + (ch & 0x000f)]; return CategoriesValue[index * 2 + offset]; } /// <summary> /// Returns the Unicode Category property for the character c. /// </summary> internal static UnicodeCategory InternalGetUnicodeCategory(string value, int index) { Debug.Assert(value != null, "value can not be null"); Debug.Assert(index < value.Length, "index < value.Length"); return (GetUnicodeCategory(InternalConvertToUtf32(value, index))); } internal static BidiCategory GetBidiCategory(string s, int index) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (((uint)index) >= ((uint)s.Length)) { throw new ArgumentOutOfRangeException(nameof(index)); } return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } internal static BidiCategory GetBidiCategory(StringBuilder s, int index) { Debug.Assert(s != null, "s can not be null"); Debug.Assert(index >= 0 && index < s.Length, "invalid index"); ; return ((BidiCategory) InternalGetCategoryValue(InternalConvertToUtf32(s, index), BIDI_CATEGORY_OFFSET)); } /// <summary> /// Get the Unicode category of the character starting at index. If the character is in BMP, charLength will return 1. /// If the character is a valid surrogate pair, charLength will return 2. /// </summary> internal static UnicodeCategory InternalGetUnicodeCategory(string str, int index, out int charLength) { Debug.Assert(str != null, "str can not be null"); Debug.Assert(str.Length > 0, "str.Length > 0"); ; Debug.Assert(index >= 0 && index < str.Length, "index >= 0 && index < str.Length"); return GetUnicodeCategory(InternalConvertToUtf32(str, index, out charLength)); } internal static bool IsCombiningCategory(UnicodeCategory uc) { Debug.Assert(uc >= 0, "uc >= 0"); return ( uc == UnicodeCategory.NonSpacingMark || uc == UnicodeCategory.SpacingCombiningMark || uc == UnicodeCategory.EnclosingMark ); } } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace HTTPlease { using Formatters; /// <summary> /// Extension methods for invocation of untyped <see cref="HttpRequest"/>s using an <see cref="HttpClient"/>. /// </summary> public static class FormatterClientExtensions { /// <summary> /// Asynchronously execute a request as an HTTP POST. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="postBody"> /// An optional object to be used as the the request body. /// </param> /// <param name="mediaType"> /// If <paramref name="postBody"/> is specified, the media type to be used /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the asynchronous operation. /// </param> /// <returns> /// An <see cref="HttpResponseMessage"/> representing the response. /// </returns> public static async Task<HttpResponseMessage> PostAsync(this HttpClient httpClient, HttpRequest request, object postBody, string mediaType, CancellationToken cancellationToken = default) { if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); if (request == null) throw new ArgumentNullException(nameof(request)); using (HttpRequestMessage requestMessage = request.BuildRequestMessage(HttpMethod.Post, postBody, mediaType, baseUri: httpClient.BaseAddress)) { return await httpClient.SendAsync(requestMessage, cancellationToken); } } /// <summary> /// Asynchronously perform an HTTP POST request, serialising the request to JSON. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="postBody"> /// The object that will be serialised into the request body. /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the operation. /// </param> /// <returns> /// A <see cref="Task{HttpResponseMessage}"/> representing the asynchronous request, whose result is the response message. /// </returns> public static Task<HttpResponseMessage> PostAsJsonAsync(this HttpClient httpClient, HttpRequest request, object postBody, CancellationToken cancellationToken = default) { return httpClient.PostAsync(request, postBody, WellKnownMediaTypes.Json, cancellationToken); } /// <summary> /// Asynchronously execute a request as an HTTP PUT. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="putBody"> /// An optional object to be used as the the request body. /// </param> /// <param name="mediaType"> /// If <paramref name="putBody"/> is specified, the media type to be used /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the asynchronous operation. /// </param> /// <returns> /// An <see cref="HttpResponseMessage"/> representing the response. /// </returns> public static async Task<HttpResponseMessage> PutAsync(this HttpClient httpClient, HttpRequest request, object putBody, string mediaType, CancellationToken cancellationToken = default) { if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); if (request == null) throw new ArgumentNullException(nameof(request)); using (HttpRequestMessage requestMessage = request.BuildRequestMessage(HttpMethod.Put, putBody, mediaType, baseUri: httpClient.BaseAddress)) { return await httpClient.SendAsync(requestMessage, cancellationToken); } } /// <summary> /// Asynchronously perform an HTTP PUT request, serialising the request to JSON. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="putBody"> /// The object that will be serialised into the request body. /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the operation. /// </param> /// <returns> /// A <see cref="Task{HttpResponseMessage}"/> representing the asynchronous request, whose result is the response message. /// </returns> public static Task<HttpResponseMessage> PutAsJsonAsync(this HttpClient httpClient, HttpRequest request, object putBody, CancellationToken cancellationToken = default) { return httpClient.PutAsync(request, putBody, WellKnownMediaTypes.Json, cancellationToken); } /// <summary> /// Asynchronously execute a request as an HTTP PATCH. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="patchBody"> /// An optional object to be used as the the request body. /// </param> /// <param name="mediaType"> /// If <paramref name="patchBody"/> is specified, the media type to be used /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the asynchronous operation. /// </param> /// <returns> /// An <see cref="HttpResponseMessage"/> representing the response. /// </returns> public static async Task<HttpResponseMessage> PatchAsync(this HttpClient httpClient, HttpRequest request, object patchBody, string mediaType, CancellationToken cancellationToken = default) { if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); if (request == null) throw new ArgumentNullException(nameof(request)); using (HttpRequestMessage requestMessage = request.BuildRequestMessage(OtherHttpMethods.Patch, patchBody, mediaType, baseUri: httpClient.BaseAddress)) { return await httpClient.SendAsync(requestMessage, cancellationToken); } } /// <summary> /// Asynchronously perform an HTTP PATCH request, serialising the request to JSON. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="patchBody"> /// The object that will be serialised into the request body. /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the operation. /// </param> /// <returns> /// A <see cref="Task{HttpResponseMessage}"/> representing the asynchronous request, whose result is the response message. /// </returns> public static Task<HttpResponseMessage> PatchAsJsonAsync(this HttpClient httpClient, HttpRequest request, object patchBody, CancellationToken cancellationToken = default) { return httpClient.PatchAsync(request, patchBody, WellKnownMediaTypes.Json, cancellationToken); } /// <summary> /// Asynchronously execute a request as an HTTP DELETE. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="deleteBody"> /// An optional object to be used as the the request body. /// </param> /// <param name="mediaType"> /// If <paramref name="deleteBody"/> is specified, the media type to be used /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the asynchronous operation. /// </param> /// <returns> /// An <see cref="HttpResponseMessage"/> representing the response. /// </returns> public static async Task<HttpResponseMessage> DeleteAsync(this HttpClient httpClient, HttpRequest request, object deleteBody, string mediaType, CancellationToken cancellationToken = default) { if (httpClient == null) throw new ArgumentNullException(nameof(httpClient)); if (request == null) throw new ArgumentNullException(nameof(request)); using (HttpRequestMessage requestMessage = request.BuildRequestMessage(HttpMethod.Delete, deleteBody, mediaType, baseUri: httpClient.BaseAddress)) { return await httpClient.SendAsync(requestMessage, cancellationToken); } } /// <summary> /// Asynchronously execute a request as an HTTP DELETE, serialising the request to JSON. /// </summary> /// <param name="httpClient"> /// The <see cref="HttpClient"/> used to execute the request. /// </param> /// <param name="request"> /// The HTTP request. /// </param> /// <param name="deleteBody"> /// An optional object to be used as the the request body. /// </param> /// <param name="cancellationToken"> /// An optional cancellation token that can be used to cancel the asynchronous operation. /// </param> /// <returns> /// An <see cref="HttpResponseMessage"/> representing the response. /// </returns> public static Task<HttpResponseMessage> DeleteAsJsonAsync(this HttpClient httpClient, HttpRequest request, object deleteBody, CancellationToken cancellationToken = default) { return httpClient.DeleteAsync(request, deleteBody, WellKnownMediaTypes.Json, cancellationToken); } } }
using System; using System.Collections.Generic; using CoreGraphics; using System.Linq; using System.Threading.Tasks; using Foundation; using UIKit; using Toggl.Phoebe.Analytics; using Toggl.Phoebe.Data; using Toggl.Phoebe.Data.DataObjects; using Toggl.Phoebe.Data.Models; using Toggl.Phoebe.Data.Views; using XPlatUtils; using Toggl.Ross.DataSources; using Toggl.Ross.Theme; using Toggl.Ross.Views; namespace Toggl.Ross.ViewControllers { public class TagSelectionViewController : UITableViewController { private const float CellSpacing = 4f; private readonly TimeEntryModel model; private List<TimeEntryTagData> modelTags; private Source source; private bool isSaving; public TagSelectionViewController (TimeEntryModel model) : base (UITableViewStyle.Plain) { this.model = model; Title = "TagTitle".Tr (); LoadTags (); } private async void LoadTags () { var dataStore = ServiceContainer.Resolve<IDataStore> (); modelTags = await dataStore.Table<TimeEntryTagData> () .QueryAsync (r => r.TimeEntryId == model.Id && r.DeletedAt == null); SetupDataSource (); } private void SetupDataSource () { var modelTagsReady = modelTags != null; if (source != null || !modelTagsReady || !IsViewLoaded) { return; } // Attach source source = new Source (this, modelTags.Select (data => data.TagId)); source.Attach (); } public override void ViewDidLoad () { base.ViewDidLoad (); View.Apply (Style.Screen); EdgesForExtendedLayout = UIRectEdge.None; SetupDataSource (); NavigationItem.RightBarButtonItem = new UIBarButtonItem ( "TagSet".Tr (), UIBarButtonItemStyle.Plain, OnNavigationBarSetClicked) .Apply (Style.NavLabelButton); } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Select Tags"; } private async void OnNavigationBarSetClicked (object s, EventArgs e) { if (isSaving) { return; } isSaving = true; try { var tags = source.SelectedTags.ToList (); // Delete unused tag relations: var deleteTasks = modelTags .Where (oldTag => !tags.Any (newTag => newTag.Id == oldTag.TagId)) .Select (data => new TimeEntryTagModel (data).DeleteAsync ()).ToList(); // Create new tag relations: var createTasks = tags .Where (newTag => !modelTags.Any (oldTag => oldTag.TagId == newTag.Id)) .Select (data => new TimeEntryTagModel () { TimeEntry = model, Tag = new TagModel (data) } .SaveAsync ()).ToList(); await Task.WhenAll (deleteTasks.Concat (createTasks)); if (deleteTasks.Count > 0 || createTasks.Count > 0) { model.Touch (); await model.SaveAsync (); } NavigationController.PopViewController (true); } finally { isSaving = false; } } private class Source : PlainDataViewSource<TagData> { private readonly static NSString TagCellId = new NSString ("EntryCellId"); private readonly TagSelectionViewController controller; private readonly HashSet<Guid> selectedTags; private UIButton newTagButton; public Source (TagSelectionViewController controller, IEnumerable<Guid> selectedTagIds) : base (controller.TableView, new WorkspaceTagsView (controller.model.Workspace.Id)) { this.controller = controller; this.selectedTags = new HashSet<Guid> (selectedTagIds); } public override void Attach () { base.Attach (); controller.TableView.RegisterClassForCellReuse (typeof (TagCell), TagCellId); controller.TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None; } public override nfloat EstimatedHeight (UITableView tableView, NSIndexPath indexPath) { return 60f; } public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { return EstimatedHeight (tableView, indexPath); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = (TagCell)tableView.DequeueReusableCell (TagCellId, indexPath); cell.Bind ((TagModel)GetRow (indexPath)); cell.Checked = selectedTags.Contains (cell.TagId); return cell; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.CellAt (indexPath) as TagCell; if (cell != null) { if (selectedTags.Remove (cell.TagId)) { cell.Checked = false; } else if (selectedTags.Add (cell.TagId)) { cell.Checked = true; } } tableView.DeselectRow (indexPath, false); } public IEnumerable<TagData> SelectedTags { get { return DataView.Data.Where (data => selectedTags.Contains (data.Id)); } } private void RefreshSelected() { foreach (var cell in TableView.VisibleCells) { var tagCell = cell as TagCell; if (tagCell != null) { tagCell.Checked = selectedTags.Contains (tagCell.TagId); } } } protected override void UpdateFooter () { base.UpdateFooter (); if (TableView.TableFooterView == null) { if (newTagButton == null) { newTagButton = new UIButton (new CGRect (0, 0, 200, 60)).Apply (Style.TagList.NewTagButton); newTagButton.SetTitle ("TagNewTag".Tr(), UIControlState.Normal); newTagButton.TouchUpInside += delegate { var vc = new NewTagViewController (controller.model.Workspace); vc.TagCreated = (tag) => { selectedTags.Add (tag.Id); RefreshSelected(); controller.NavigationController.PopToViewController (controller, true); }; controller.NavigationController.PushViewController (vc, true); }; } TableView.TableFooterView = newTagButton; } } } private class TagCell : ModelTableViewCell<TagModel> { private readonly UILabel nameLabel; public TagCell (IntPtr handle) : base (handle) { this.Apply (Style.Screen); ContentView.Add (nameLabel = new UILabel ().Apply (Style.TagList.NameLabel)); BackgroundView = new UIView ().Apply (Style.TagList.RowBackground); } public override void LayoutSubviews () { base.LayoutSubviews (); var contentFrame = new CGRect (0, CellSpacing / 2, Frame.Width, Frame.Height - CellSpacing); SelectedBackgroundView.Frame = BackgroundView.Frame = ContentView.Frame = contentFrame; contentFrame.X = 15f; contentFrame.Y = 0; contentFrame.Width -= 15f; if (Checked) { // Adjust for the checkbox accessory contentFrame.Width -= 40f; } nameLabel.Frame = contentFrame; } protected override void ResetTrackedObservables () { Tracker.MarkAllStale (); if (DataSource != null) { Tracker.Add (DataSource, HandleTagPropertyChanged); } Tracker.ClearStale (); } private void HandleTagPropertyChanged (string prop) { if (prop == TagModel.PropertyName) { Rebind (); } } protected override void Rebind () { ResetTrackedObservables (); if (DataSource == null) { return; } if (String.IsNullOrWhiteSpace (DataSource.Name)) { nameLabel.Text = "TagNoNameTag".Tr (); } else { nameLabel.Text = DataSource.Name; } } public bool Checked { get { return Accessory == UITableViewCellAccessory.Checkmark; } set { Accessory = value ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None; SetNeedsLayout (); } } public Guid TagId { get { if (DataSource != null) { return DataSource.Id; } return Guid.Empty; } } } } }
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Azure.ServiceBus.Core.Tests { using System; using System.Threading.Tasks; using Context; using NUnit.Framework; [TestFixture] public class TopologyCorrelationId_Specs : AzureServiceBusTestFixture { [Test] public async Task Should_handle_base_event_class() { var transactionId = NewId.NextGuid(); await InputQueueSendEndpoint.Send<INewUserEvent>(new { TransactionId = transactionId }); ConsumeContext<INewUserEvent> context = await _handled; Assert.IsTrue(context.CorrelationId.HasValue); Assert.That(context.CorrelationId.Value, Is.EqualTo(transactionId)); } [Test] public async Task Should_handle_named_configured_legacy() { var transactionId = NewId.NextGuid(); await InputQueueSendEndpoint.Send<LegacyMessage>(new { TransactionId = transactionId }); ConsumeContext<LegacyMessage> legacyContext = await _legacyHandled; Assert.IsTrue(legacyContext.CorrelationId.HasValue); Assert.That(legacyContext.CorrelationId.Value, Is.EqualTo(transactionId)); } [Test] public async Task Should_handle_named_property() { var transactionId = NewId.NextGuid(); await InputQueueSendEndpoint.Send<OtherMessage>(new { CorrelationId = transactionId }); ConsumeContext<OtherMessage> otherContext = await _otherHandled; Assert.IsTrue(otherContext.CorrelationId.HasValue); Assert.That(otherContext.CorrelationId.Value, Is.EqualTo(transactionId)); } Task<ConsumeContext<INewUserEvent>> _handled; Task<ConsumeContext<OtherMessage>> _otherHandled; Task<ConsumeContext<LegacyMessage>> _legacyHandled; protected override void ConfigureServiceBusBusHost(IServiceBusBusFactoryConfigurator configurator, IServiceBusHost host) { MessageCorrelation.UseCorrelationId<LegacyMessage>(x => x.TransactionId); configurator.Send<IEvent>(x => { x.UseCorrelationId(p => p.TransactionId); }); } protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator) { _handled = Handled<INewUserEvent>(configurator); _otherHandled = Handled<OtherMessage>(configurator); _legacyHandled = Handled<LegacyMessage>(configurator); } public interface IEvent { Guid TransactionId { get; } } public interface INewUserEvent : IEvent { } public class OtherMessage { public Guid CorrelationId { get; set; } } public class LegacyMessage { public Guid TransactionId { get; set; } } } [TestFixture] public class TopologySetParitioning_Specs : AzureServiceBusTestFixture { [Test] public async Task Should_handle_named_property() { var transactionId = NewId.NextGuid(); await Bus.Publish<PartitionedMessage>(new { CorrelationId = transactionId }); ConsumeContext<PartitionedMessage> otherContext = await _otherHandled; Assert.IsTrue(otherContext.CorrelationId.HasValue); Assert.That(otherContext.CorrelationId.Value, Is.EqualTo(transactionId)); } Task<ConsumeContext<PartitionedMessage>> _otherHandled; protected override void ConfigureServiceBusBusHost(IServiceBusBusFactoryConfigurator configurator, IServiceBusHost host) { configurator.Send<PartitionedMessage>(x => { x.UsePartitionKeyFormatter(p => p.Message.CorrelationId.ToString("N")); }); configurator.Publish<PartitionedMessage>(x => { x.EnablePartitioning = true; //x.EnableExpress = true; }); configurator.ReceiveEndpoint(host, "partitioned-input-queue", x => { x.EnablePartitioning = true; _otherHandled = Handled<PartitionedMessage>(x); }); } protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator) { } public interface PartitionedMessage { Guid CorrelationId { get; } } } [TestFixture] public class TopologySetParitioningSubscription_Specs : AzureServiceBusTestFixture { [Test] public async Task Should_handle_named_property() { var transactionId = NewId.NextGuid(); await Bus.Publish<PartitionedMessage>(new { CorrelationId = transactionId }); ConsumeContext<PartitionedMessage> otherContext = await _otherHandled; Assert.IsTrue(otherContext.CorrelationId.HasValue); Assert.That(otherContext.CorrelationId.Value, Is.EqualTo(transactionId)); } Task<ConsumeContext<PartitionedMessage>> _otherHandled; protected override void ConfigureServiceBusBusHost(IServiceBusBusFactoryConfigurator configurator, IServiceBusHost host) { configurator.Send<PartitionedMessage>(x => { x.UsePartitionKeyFormatter(p => p.Message.CorrelationId.ToString("N")); }); configurator.Publish<PartitionedMessage>(x => { x.EnablePartitioning = true; //x.EnableExpress = true; }); configurator.SubscriptionEndpoint<PartitionedMessage>(host, "part-sub", x => { _otherHandled = Handled<PartitionedMessage>(x); }); } protected override void ConfigureServiceBusReceiveEndpoint(IServiceBusReceiveEndpointConfigurator configurator) { } public interface PartitionedMessage { Guid CorrelationId { get; } } } }
// // TagSelectionWidget.cs // // Author: // Ruben Vermeersch <[email protected]> // Mike Gemuende <[email protected]> // // Copyright (C) 2008-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // Copyright (C) 2009 Mike Gemuende // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections.Generic; using System; using Gdk; using Gtk; using Mono.Unix; using FSpot.Core; using FSpot.Database; using FSpot.Settings; using FSpot.Utils; using FSpot.Widgets; using Hyena.Widgets; namespace FSpot { public class TagSelectionWidget : SaneTreeView { readonly Db database; TagStore tag_store; // FIXME this is a hack. static Pixbuf empty_pixbuf = new Pixbuf (Colorspace.Rgb, true, 8, 1, 1); // If these are changed, the base () call in the constructor must be updated. const int IdColumn = 0; const int NameColumn = 1; // Selection management. public Tag TagAtPosition (double x, double y) { return TagAtPosition((int) x, (int) y); } public Tag TagAtPosition (int x, int y) { TreePath path; // Work out which tag we're dropping onto if (!GetPathAtPos (x, y, out path)) return null; return TagByPath (path); } public Tag TagByPath (TreePath path) { TreeIter iter; if (!Model.GetIter (out iter, path)) return null; return TagByIter (iter); } public Tag TagByIter (TreeIter iter) { GLib.Value val = new GLib.Value (); Model.GetValue (iter, IdColumn, ref val); uint tag_id = (uint) val; return tag_store.Get (tag_id); } // Loading up the store. void LoadCategory (Category category, TreeIter parent_iter) { IList<Tag> tags = category.Children; foreach (Tag t in tags) { TreeIter iter = (Model as TreeStore).AppendValues (parent_iter, t.Id, t.Name); if (t is Category) LoadCategory (t as Category, iter); } } public void ScrollTo (Tag tag) { TreeIter iter; if (! TreeIterForTag (tag, out iter)) return; TreePath path = Model.GetPath (iter); ScrollToCell (path, null, false, 0, 0); } public Tag [] TagHighlight { get { TreeModel model; TreeIter iter; TreePath [] rows = Selection.GetSelectedRows(out model); Tag [] tags = new Tag [rows.Length]; int i = 0; foreach (TreePath path in rows) { GLib.Value value = new GLib.Value (); Model.GetIter (out iter, path); Model.GetValue (iter, IdColumn, ref value); uint tag_id = (uint) value; tags[i] = tag_store.Get (tag_id); i++; } return tags; } set { if (value == null) return; Selection.UnselectAll (); TreeIter iter; foreach (Tag tag in value) if (TreeIterForTag (tag, out iter)) Selection.SelectIter (iter); } } public void Update () { (Model as TreeStore).Clear (); // GRRR We have to special case the root because I can't pass null for a // Gtk.TreeIter (since it's a struct, and not a class). // FIXME: This should be fixed in GTK#... It's gross. foreach (Tag t in tag_store.RootCategory.Children) { TreeIter iter = (Model as TreeStore).AppendValues (t.Id, t.Name); if (t is Category) LoadCategory (t as Category, iter); } } // Data functions. void SetBackground (CellRenderer renderer, Tag tag) { // FIXME this should be themable but Gtk# doesn't give me access to the proper // members in GtkStyle for that. /* if (tag is Category) renderer.CellBackground = ToHashColor (this.Style.MidColors [(int) Gtk.StateType.Normal]); else renderer.CellBackground = ToHashColor (this.Style.LightColors [(int) Gtk.StateType.Normal]); */ } void IconDataFunc (TreeViewColumn column, CellRenderer renderer, TreeModel model, TreeIter iter) { GLib.Value value = new GLib.Value (); Model.GetValue (iter, IdColumn, ref value); uint tag_id = (uint) value; Tag tag = tag_store.Get (tag_id); if (tag == null) return; SetBackground (renderer, tag); if (tag.SizedIcon != null) { Cms.Profile screen_profile; if (FSpot.ColorManagement.Profiles.TryGetValue (Preferences.Get<string> (Preferences.ColorManagementDisplayProfile), out screen_profile)) { //FIXME, we're leaking a pixbuf here using (Gdk.Pixbuf temp = tag.SizedIcon.Copy ()) { FSpot.ColorManagement.ApplyProfile (temp, screen_profile); (renderer as CellRendererPixbuf).Pixbuf = temp; } } else (renderer as CellRendererPixbuf).Pixbuf = tag.SizedIcon; } else (renderer as CellRendererPixbuf).Pixbuf = empty_pixbuf; } void NameDataFunc (TreeViewColumn column, CellRenderer renderer, TreeModel model, TreeIter iter) { // FIXME not sure why it happens... if (model == null) return; GLib.Value value = new GLib.Value (); Model.GetValue (iter, IdColumn, ref value); uint tag_id = (uint) value; Tag tag = tag_store.Get (tag_id); if (tag == null) return; SetBackground (renderer, tag); (renderer as CellRendererText).Text = tag.Name; } bool TreeIterForTag(Tag tag, out TreeIter iter) { TreeIter root = TreeIter.Zero; iter = TreeIter.Zero; bool valid = Model.GetIterFirst (out root); while (valid) { if (TreeIterForTagRecurse (tag, root, out iter)) return true; valid = Model.IterNext (ref root); } return false; } // Depth first traversal bool TreeIterForTagRecurse (Tag tag, TreeIter parent, out TreeIter iter) { bool valid = Model.IterChildren (out iter, parent); while (valid) { if (TreeIterForTagRecurse (tag, iter, out iter)) return true; valid = Model.IterNext (ref iter); } GLib.Value value = new GLib.Value (); Model.GetValue (parent, IdColumn, ref value); iter = parent; if (tag.Id == (uint) value) return true; return false; } // Copy a branch of the tree to a new parent // (note, this doesn't work generically as it only copies the first value of each node) void CopyBranch (TreeIter src, TreeIter dest, bool is_root, bool is_parent) { TreeIter copy, iter; GLib.Value value = new GLib.Value (); TreeStore store = Model as TreeStore; bool valid; store.GetValue (src, IdColumn, ref value); Tag tag = tag_store.Get ((uint)value); if (is_parent) { // we need to figure out where to insert it in the correct order copy = InsertInOrder(dest, is_root, tag); } else { copy = store.AppendValues (dest, (uint)value, tag.Name); } valid = Model.IterChildren (out iter, src); while (valid) { // child nodes are already ordered CopyBranch (iter, copy, false, false); valid = Model.IterNext (ref iter); } } // insert tag into the correct place in the tree, with parent. return the new TagIter in iter. TreeIter InsertInOrder (TreeIter parent, bool is_root, Tag tag) { TreeStore store = Model as TreeStore; TreeIter iter; Tag compare; bool valid; if (is_root) valid = store.GetIterFirst (out iter); else valid = store.IterChildren (out iter, parent); while (valid) { //I have no desire to figure out a more performant sort over this... GLib.Value value = new GLib.Value (); store.GetValue(iter, IdColumn, ref value); compare = tag_store.Get ((uint) value); if (compare.CompareTo (tag) > 0) { iter = store.InsertNodeBefore (iter); store.SetValue (iter, IdColumn, tag.Id); store.SetValue (iter, NameColumn, tag.Name); if (!is_root) ExpandRow (Model.GetPath (parent), false); return iter; } valid = store.IterNext(ref iter); } if (is_root) iter = store.AppendNode (); else { iter = store.AppendNode (parent); ExpandRow (Model.GetPath (parent), false); } store.SetValue (iter, IdColumn, tag.Id); store.SetValue (iter, NameColumn, tag.Name); return iter; } void HandleTagsRemoved (object sender, DbItemEventArgs<Tag> args) { TreeIter iter; foreach (Tag tag in args.Items) { if (TreeIterForTag (tag, out iter)) (Model as TreeStore).Remove (ref iter); } } void HandleTagsAdded (object sender, DbItemEventArgs<Tag> args) { TreeIter iter = TreeIter.Zero; foreach (Tag tag in args.Items) { if (tag.Category != tag_store.RootCategory) TreeIterForTag (tag.Category, out iter); InsertInOrder (iter, tag.Category.Name == tag_store.RootCategory.Name, tag); } } void HandleTagsChanged (object sender, DbItemEventArgs<Tag> args) { TreeStore store = Model as TreeStore; TreeIter iter, category_iter, parent_iter; foreach (Tag tag in args.Items) { TreeIterForTag (tag, out iter); bool category_valid = TreeIterForTag(tag.Category, out category_iter); bool parent_valid = Model.IterParent(out parent_iter, iter); if ((category_valid && (category_iter.Equals (parent_iter))) || (!category_valid && !parent_valid)) { // if we haven't been reparented TreePath path = store.GetPath (iter); store.EmitRowChanged (path, iter); } else { // It is a bit tougher. We need to do an annoying clone of structs... CopyBranch (iter, category_iter, !category_valid, true); store.Remove (ref iter); } } } void ExpandDefaults () { int [] tags = Preferences.Get<int []> (Preferences.ExpandedTags); if (tags == null) { ExpandAll (); return; } TreeIter [] iters = ModelIters (); if (iters == null || iters.Length == 0 || tags.Length == 0) return; foreach (TreeIter iter in iters) { GLib.Value v = new GLib.Value (); Model.GetValue (iter, IdColumn, ref v); int tag_id = (int)(uint) v; if (Array.IndexOf (tags, tag_id) > -1) { ExpandRow (Model.GetPath (iter), false); } } } /// <summary> /// Returns a flattened array of TreeIter's from the Model /// </summary> /// <returns> /// TreeIter [] /// </returns> TreeIter [] ModelIters () { TreeIter root; if (Model.GetIterFirst (out root)) { return ModelIters (root, true).ToArray (); } return null; } // Returns a List containing the root TreeIter and all TreeIters at root's level and // descended from it List<TreeIter> ModelIters (TreeIter root, bool first) { List<TreeIter> model_iters = new List<TreeIter> (Model.IterNChildren ()); model_iters.Add (root); // Append any children TreeIter child; if (Model.IterChildren (out child, root)) model_iters.AddRange (ModelIters (child, true)); // Append any siblings and their children if (first) { while (Model.IterNext (ref root)) { model_iters.AddRange (ModelIters (root, false)); } } return model_iters; } public void SaveExpandDefaults () { List<int> expanded_tags = new List<int> (); TreeIter [] iters = ModelIters (); if (iters == null) return; foreach (TreeIter iter in iters) { if (GetRowExpanded (Model.GetPath (iter))) { GLib.Value v = new GLib.Value (); Model.GetValue (iter, IdColumn, ref v); expanded_tags.Add ((int)(uint) v); } } Preferences.Set (Preferences.ExpandedTags, expanded_tags.ToArray ()); } public void EditSelectedTagName () { TreePath [] rows = Selection.GetSelectedRows(); if (rows.Length != 1) return; //SetCursor (rows[0], NameColumn, true); text_render.Editable = true; text_render.Edited += HandleTagNameEdited; SetCursor (rows[0], complete_column, true); text_render.Editable = false; } public void HandleTagNameEdited (object sender, EditedArgs args) { args.RetVal = false; TreeIter iter; if (!Model.GetIterFromString (out iter, args.Path)) return; GLib.Value value = new GLib.Value (); Model.GetValue (iter, IdColumn, ref value); uint tag_id = (uint) value; Tag tag = tag_store.Get (tag_id); // Ignore if it hasn't changed if (tag.Name == args.NewText) return; // Check that the tag doesn't already exist if (string.Compare (args.NewText, tag.Name, true) != 0 && tag_store.GetTagByName (args.NewText) != null) { HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, MessageType.Warning, ButtonsType.Ok, Catalog.GetString ("Error renaming tag"), Catalog.GetString ("This name is already in use")); md.Run (); md.Destroy (); this.GrabFocus (); return; } tag.Name = args.NewText; tag_store.Commit (tag, true); text_render.Edited -= HandleTagNameEdited; args.RetVal = true; } static TargetList tagSourceTargetList = new TargetList(); static TargetList tagDestTargetList = new TargetList(); static TagSelectionWidget() { tagSourceTargetList.AddTargetEntry(DragDropTargets.TagListEntry); tagDestTargetList.AddTargetEntry(DragDropTargets.PhotoListEntry); tagDestTargetList.AddUriTargets((uint)DragDropTargets.TargetType.UriList); tagDestTargetList.AddTargetEntry(DragDropTargets.TagListEntry); } CellRendererPixbuf pix_render; TreeViewColumn complete_column; CellRendererText text_render; protected TagSelectionWidget (IntPtr raw) : base (raw) { } // Constructor. public TagSelectionWidget (TagStore tag_store) : base (new TreeStore (typeof(uint), typeof(string))) { database = App.Instance.Database; HeadersVisible = false; complete_column = new TreeViewColumn (); pix_render = new CellRendererPixbuf (); complete_column.PackStart (pix_render, false); complete_column.SetCellDataFunc (pix_render, new TreeCellDataFunc (IconDataFunc)); //complete_column.AddAttribute (pix_render, "pixbuf", OpenIconColumn); //icon_column = AppendColumn ("icon", //, new TreeCellDataFunc (IconDataFunc)); //icon_column = AppendColumn ("icon", new CellRendererPixbuf (), new TreeCellDataFunc (IconDataFunc)); text_render = new CellRendererText (); complete_column.PackStart (text_render, true); complete_column.SetCellDataFunc (text_render, new TreeCellDataFunc (NameDataFunc)); AppendColumn (complete_column); this.tag_store = tag_store; Update (); ExpandDefaults (); tag_store.ItemsAdded += HandleTagsAdded; tag_store.ItemsRemoved += HandleTagsRemoved; tag_store.ItemsChanged += HandleTagsChanged; // TODO make the search find tags that are not currently expanded EnableSearch = true; SearchColumn = NameColumn; // Transparent white empty_pixbuf.Fill(0xffffff00); /* set up drag and drop */ DragDataGet += HandleDragDataGet; DragDrop += HandleDragDrop; DragBegin += HandleDragBegin; Gtk.Drag.SourceSet (this, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask, (TargetEntry[])tagSourceTargetList, DragAction.Copy | DragAction.Move); DragDataReceived += HandleDragDataReceived; DragMotion += HandleDragMotion; Gtk.Drag.DestSet (this, DestDefaults.All, (TargetEntry[])tagDestTargetList, DragAction.Copy | DragAction.Move); } void HandleDragBegin (object sender, DragBeginArgs args) { Tag [] tags = TagHighlight; int len = tags.Length; int size = 32; int csize = size/2 + len * size / 2 + 2; Pixbuf container = new Pixbuf (Gdk.Colorspace.Rgb, true, 8, csize, csize); container.Fill (0x00000000); bool use_icon = false;; while (len-- > 0) { Pixbuf thumbnail = tags[len].Icon; if (thumbnail != null) { Pixbuf small = thumbnail.ScaleToMaxSize (size, size); int x = len * (size/2) + (size - small.Width)/2; int y = len * (size/2) + (size - small.Height)/2; small.Composite (container, x, y, small.Width, small.Height, x, y, 1.0, 1.0, Gdk.InterpType.Nearest, 0xff); small.Dispose (); use_icon = true; } } if (use_icon) Gtk.Drag.SetIconPixbuf (args.Context, container, 0, 0); container.Dispose (); } void HandleDragDataGet (object sender, DragDataGetArgs args) { if (args.Info == DragDropTargets.TagListEntry.Info) { args.SelectionData.SetTagsData (TagHighlight, args.Context.Targets[0]); } } void HandleDragDrop (object sender, DragDropArgs args) { args.RetVal = true; } public void HandleDragMotion (object o, DragMotionArgs args) { TreePath path; TreeViewDropPosition position = TreeViewDropPosition.IntoOrAfter; GetPathAtPos (args.X, args.Y, out path); if (path == null) return; // Tags can be dropped into another tag SetDragDestRow (path, position); // Scroll if within 20 pixels of the top or bottom of the tag list if (args.Y < 20) Vadjustment.Value -= 30; else if (((o as Gtk.Widget).Allocation.Height - args.Y) < 20) Vadjustment.Value += 30; } public void HandleDragDataReceived (object o, DragDataReceivedArgs args) { TreePath path; TreeViewDropPosition position; if ( ! GetDestRowAtPos ((int)args.X, (int)args.Y, out path, out position)) return; Tag tag = path == null ? null : TagByPath (path); if (tag == null) return; if (args.Info == DragDropTargets.PhotoListEntry.Info) { database.BeginTransaction (); Photo[] photos = args.SelectionData.GetPhotosData (); foreach (Photo photo in photos) { if (photo == null) continue; photo.AddTag (tag); database.Photos.Commit (photo); // FIXME: AddTagExtendes from Mainwindow.cs does some tag-icon handling. // this should be done here or completely located to the Tag-class. } database.CommitTransaction (); // FIXME: this needs to be done somewhere: //query_widget.PhotoTagsChanged (new Tag[] {tag}); return; } if (args.Info == (uint)DragDropTargets.TargetType.UriList) { UriList list = args.SelectionData.GetUriListData (); database.BeginTransaction (); List<Photo> photos = new List<Photo> (); foreach (var photo_uri in list) { Photo photo = database.Photos.GetByUri (photo_uri); // FIXME - at this point we should import the photo, and then continue if (photo == null) continue; // FIXME this should really follow the AddTagsExtended path too photo.AddTag (new Tag[] {tag}); photos.Add (photo); } database.Photos.Commit (photos.ToArray ()); database.CommitTransaction (); // FIXME: this need to be done //InvalidateViews (); // but it seems not to be needed. tags are updated through in IconView through PhotoChanged return; } if (args.Info == DragDropTargets.TagListEntry.Info) { Category parent; if (position == TreeViewDropPosition.Before || position == TreeViewDropPosition.After) { parent = tag.Category; } else { parent = tag as Category; } if (parent == null || TagHighlight.Length < 1) { args.RetVal = false; return; } int moved_count = 0; Tag [] highlighted_tags = TagHighlight; foreach (Tag child in TagHighlight) { // FIXME with this reparenting via dnd, you cannot move a tag to root. if (child != parent && child.Category != parent && !child.IsAncestorOf(parent)) { child.Category = parent; // Saving changes will automatically cause the TreeView to be updated database.Tags.Commit (child); moved_count++; } } // Reselect the same tags TagHighlight = highlighted_tags; args.RetVal = moved_count > 0; } } #if TEST_TAG_SELECTION_WIDGET class Test { private TagSelectionWidget selection_widget; private void OnSelectionChanged () { Log.Debug ("Selection changed:"); foreach (Tag t in selection_widget.TagSelection) Log.DebugFormat ("\t{0}", t.Name); } private Test () { const string path = "/tmp/TagSelectionTest.db"; try { File.Delete (path); } catch {} Db db = new Db (path, true); Category people_category = db.Tags.CreateCategory (null, "People"); db.Tags.CreateTag (people_category, "Anna"); db.Tags.CreateTag (people_category, "Ettore"); db.Tags.CreateTag (people_category, "Miggy"); db.Tags.CreateTag (people_category, "Nat"); Category places_category = db.Tags.CreateCategory (null, "Places"); db.Tags.CreateTag (places_category, "Milan"); db.Tags.CreateTag (places_category, "Boston"); Category exotic_category = db.Tags.CreateCategory (places_category, "Exotic"); db.Tags.CreateTag (exotic_category, "Bengalore"); db.Tags.CreateTag (exotic_category, "Manila"); db.Tags.CreateTag (exotic_category, "Tokyo"); selection_widget = new TagSelectionWidget (db.Tags); selection_widget.SelectionChanged += new SelectionChangedHandler (OnSelectionChanged); Window window = new Window (WindowType.Toplevel); window.SetDefaultSize (400, 200); ScrolledWindow scrolled = new ScrolledWindow (null, null); scrolled.SetPolicy (PolicyType.Automatic, PolicyType.Automatic); scrolled.Add (selection_widget); window.Add (scrolled); window.ShowAll (); } static private void Main (string [] args) { Program program = new Program ("TagSelectionWidgetTest", "0.0", Modules.UI, args); Test test = new Test (); program.Run (); } } #endif } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Graphics; #if FRB_MDX using System.Drawing; using Microsoft.DirectX; #else //if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; #endif namespace FlatRedBall.Math.Geometry { public class Capsule2D : PositionedObject, IEquatable<Capsule2D> { #region Fields internal static Circle CollisionCircle = new Circle(); internal static Polygon CollisionPolygon = Polygon.CreateRectangle(1, 1); // The following two members are internal so the Renderer can access them for speed during rendering. internal float mEndpointRadius = .5f; internal float mScale = 1; bool mVisible; Color mColor = Color.White; internal Layer mLayerBelongingTo; #endregion #region Properties public float BoundingRadius { get { return mScale + mEndpointRadius; } } public Color Color { get { return mColor; } set { mColor = value; } } public float EndpointRadius { get { return mEndpointRadius; } set { mEndpointRadius = value; } } public Vector3 Endpoint1Position { get { Vector3 returnValue = new Vector3(mScale - mEndpointRadius, 0, 0); FlatRedBall.Math.MathFunctions.TransformVector(ref returnValue, ref mRotationMatrix); returnValue += Position; return returnValue; } } public Vector3 Endpoint2Position { get { Vector3 returnValue = new Vector3 ( -mScale + mEndpointRadius, 0, 0); FlatRedBall.Math.MathFunctions.TransformVector(ref returnValue, ref mRotationMatrix); returnValue += Position; return returnValue; } } public float Scale { get { return mScale; } set { #if DEBUG if (value < 0) { throw new ArgumentException("Cannot set a negative scale value. This will cause collision to behave weird."); } #endif mScale = value; } } public Segment TopSegment { get { Point rightPoint = new Point(mScale - mEndpointRadius, mEndpointRadius); Point leftPoint = new Point(-mScale + mEndpointRadius, mEndpointRadius); FlatRedBall.Math.MathFunctions.TransformPoint(ref leftPoint, ref mRotationMatrix); FlatRedBall.Math.MathFunctions.TransformPoint(ref rightPoint, ref mRotationMatrix); rightPoint.X += Position.X; rightPoint.Y += Position.Y; leftPoint.X += Position.X; leftPoint.Y += Position.Y; return new Segment(leftPoint, rightPoint); } } public Segment BottomSegment { get { Point rightPoint = new Point(mScale - mEndpointRadius, -mEndpointRadius); Point leftPoint = new Point(-mScale + mEndpointRadius, -mEndpointRadius); FlatRedBall.Math.MathFunctions.TransformPoint(ref leftPoint, ref mRotationMatrix); FlatRedBall.Math.MathFunctions.TransformPoint(ref rightPoint, ref mRotationMatrix); leftPoint.X += Position.X; leftPoint.Y += Position.Y; rightPoint.X += Position.X; rightPoint.Y += Position.Y; return new Segment(leftPoint, rightPoint); } } public bool Visible { get { return mVisible; } set { if (value != mVisible) { mVisible = value; ShapeManager.NotifyOfVisibilityChange(this); } } } #endregion #region Methods #region Public Methods public Capsule2D Clone() { Capsule2D clonedCapsule = this.Clone<Capsule2D>(); clonedCapsule.mVisible = false; clonedCapsule.mLayerBelongingTo = null; return clonedCapsule; } public bool CollideAgainst(Capsule2D otherCapsule) { this.UpdateDependencies(TimeManager.CurrentTime); otherCapsule.UpdateDependencies(TimeManager.CurrentTime); #region Create some initial variables which will be used below Vector3 thisEndpoint1 = this.Endpoint1Position; Vector3 thisEndpoint2 = this.Endpoint2Position; Vector3 otherEndpoint1 = otherCapsule.Endpoint1Position; Vector3 otherEndpoint2 = otherCapsule.Endpoint2Position; #endregion #region Point vs. Point (circle collision) float radiiCombinedSquared = (mEndpointRadius + otherCapsule.mEndpointRadius) * (mEndpointRadius + otherCapsule.mEndpointRadius); Vector3 difference1 = thisEndpoint1 - otherEndpoint1; Vector3 difference2 = thisEndpoint1 - otherEndpoint2; Vector3 difference3 = thisEndpoint2 - otherEndpoint1; Vector3 difference4 = thisEndpoint2 - otherEndpoint2; if ( #if FRB_MDX difference1.LengthSq() < radiiCombinedSquared || difference2.LengthSq() < radiiCombinedSquared || difference3.LengthSq() < radiiCombinedSquared || difference4.LengthSq() < radiiCombinedSquared) #else //if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE difference1.LengthSquared() < radiiCombinedSquared || difference2.LengthSquared() < radiiCombinedSquared || difference3.LengthSquared() < radiiCombinedSquared || difference4.LengthSquared() < radiiCombinedSquared) #endif { return true; } #endregion #region Segment vs. Segment (bandaid collision) Segment thisTopSegment = this.TopSegment; Segment thisBottomSegment = this.BottomSegment; Segment otherTopSegment = otherCapsule.TopSegment; Segment otherBottomSegment = otherCapsule.BottomSegment; if ( thisTopSegment.Intersects(otherTopSegment) || thisTopSegment.Intersects(otherBottomSegment) || thisBottomSegment.Intersects(otherTopSegment) || thisBottomSegment.Intersects(otherBottomSegment)) { return true; } #endregion #region Point vs. Segment (T collision) if ( thisTopSegment.DistanceTo(otherEndpoint1.X, otherEndpoint1.Y) < otherCapsule.mEndpointRadius || thisTopSegment.DistanceTo(otherEndpoint2.X, otherEndpoint2.Y) < otherCapsule.mEndpointRadius || thisBottomSegment.DistanceTo(otherEndpoint1.X, otherEndpoint1.Y) < otherCapsule.mEndpointRadius || thisBottomSegment.DistanceTo(otherEndpoint2.X, otherEndpoint2.Y) < otherCapsule.mEndpointRadius) { return true; } if ( otherTopSegment.DistanceTo(thisEndpoint1.X, thisEndpoint1.Y) < this.mEndpointRadius || otherTopSegment.DistanceTo(thisEndpoint2.X, thisEndpoint2.Y) < this.mEndpointRadius || otherBottomSegment.DistanceTo(thisEndpoint1.X, thisEndpoint1.Y) < this.mEndpointRadius || otherBottomSegment.DistanceTo(thisEndpoint2.X, thisEndpoint2.Y) < this.mEndpointRadius) { return true; } #endregion #region Endpoint inside Shape (Fully contained collision) Point thisEndpoint1Point = new Point(ref thisEndpoint1); Point thisEndpoint2Point = new Point(ref thisEndpoint2); Point otherEndpoint1Point = new Point(ref otherEndpoint1); Point otherEndpoint2Point = new Point(ref otherEndpoint2); if ( MathFunctions.IsPointInsideRectangle(thisEndpoint1Point, otherTopSegment.Point1, otherTopSegment.Point2, otherBottomSegment.Point2, otherBottomSegment.Point1) || MathFunctions.IsPointInsideRectangle(thisEndpoint2Point, otherTopSegment.Point1, otherTopSegment.Point2, otherBottomSegment.Point2, otherBottomSegment.Point1) || MathFunctions.IsPointInsideRectangle(otherEndpoint1Point, thisTopSegment.Point1, thisTopSegment.Point2, thisBottomSegment.Point2, thisBottomSegment.Point1) || MathFunctions.IsPointInsideRectangle(otherEndpoint2Point, thisTopSegment.Point1, thisTopSegment.Point2, thisBottomSegment.Point2, thisBottomSegment.Point1) ) { return true; } #endregion // If we got here then the two do not touch. return false; } public bool CollideAgainst(AxisAlignedRectangle axisAlignedRectangle) { return axisAlignedRectangle.CollideAgainst(this); } public bool CollideAgainst(Circle circle) { return circle.CollideAgainst(this); } public bool CollideAgainst(Line line) { return line.CollideAgainst(this); } public bool CollideAgainst(Polygon polygon) { return polygon.CollideAgainst(this); } public bool CollideAgainstMove(Capsule2D otherCapsule, float thisMass, float otherMass) { throw new NotImplementedException("This method is not implemented. Capsules are intended only for CollideAgainst - use Polygons for CollideAgainstMove and CollideAgainstBounce"); } public bool CollideAgainstMove(AxisAlignedRectangle axisAlignedRectangle, float thisMass, float otherMass) { return axisAlignedRectangle.CollideAgainstMove(this, otherMass, thisMass); } public bool CollideAgainstMove(Circle circle, float thisMass, float otherMass) { return circle.CollideAgainstMove(this, otherMass, thisMass); } public bool CollideAgainstMove(Line line, float thisMass, float otherMass) { return line.CollideAgainstMove(this, otherMass, thisMass); } public bool CollideAgainstMove(Polygon polygon, float thisMass, float otherMass) { return polygon.CollideAgainstMove(this, otherMass, thisMass); } public bool CollideAgainstBounce(Capsule2D capsule2D, float thisMass, float otherMass, float elasticity) { throw new NotImplementedException("This method is not implemented. Capsules are intended only for CollideAgainst - use Polygons for CollideAgainstMove and CollideAgainstBounce"); } public bool CollideAgainstBounce(AxisAlignedRectangle axisAlignedRectangle, float thisMass, float otherMass, float elasticity) { return axisAlignedRectangle.CollideAgainstBounce(this, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Circle circle, float thisMass, float otherMass, float elasticity) { return circle.CollideAgainstBounce(this, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Line line, float thisMass, float otherMass, float elasticity) { return line.CollideAgainstBounce(this, otherMass, thisMass, elasticity); } public bool CollideAgainstBounce(Polygon polygon, float thisMass, float otherMass, float elasticity) { return polygon.CollideAgainstBounce(this, otherMass, thisMass, elasticity); } #endregion #endregion #region IEquatable<Capsule2D> Members bool IEquatable<Capsule2D>.Equals(Capsule2D other) { return this == other; } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Windows.Forms; using DotSpatial.Data; namespace DotSpatial.Symbology.Forms { /// <summary> /// BreakSliderGraph. /// </summary> [DefaultEvent("SliderMoved")] public class BreakSliderGraph : Control { #region Fields private readonly ContextMenu _contextMenu; private readonly BarGraph _graph; private readonly Statistics _statistics; private Color _breakColor; private bool _dragCursor; private string _fieldName; private bool _isDragging; private bool _isRaster; private string _normalizationField; private IRaster _raster; private IRasterLayer _rasterLayer; private IRasterSymbolizer _rasterSymbolizer; private IFeatureScheme _scheme; private Color _selectedBreakColor; private BreakSlider _selectedSlider; private IAttributeSource _source; private DataTable _table; private List<double> _values; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BreakSliderGraph"/> class. /// </summary> public BreakSliderGraph() { _graph = new BarGraph(Width, Height); MaximumSampleSize = 10000; Breaks = new List<BreakSlider>(); _selectedBreakColor = Color.Red; _breakColor = Color.Blue; TitleFont = new Font("Arial", 20, FontStyle.Bold); BorderStyle = BorderStyle.Fixed3D; _contextMenu = new ContextMenu(); _contextMenu.MenuItems.Add("Reset Zoom", ResetZoomClicked); _contextMenu.MenuItems.Add("Zoom To Categories", CategoryZoomClicked); _statistics = new Statistics(); } #endregion #region Events /// <summary> /// Occurs after the slider has been completely repositioned. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderMoved; /// <summary> /// Occurs when manual break sliding begins so that the mode can be /// switched to manual, rather than showing equal breaks or something. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderMoving; /// <summary> /// Occurs when a click in a range changes the slider that is selected. /// </summary> public event EventHandler<BreakSliderEventArgs> SliderSelected; /// <summary> /// Occurs after the statistics have been re-calculated. /// </summary> public event EventHandler<StatisticalEventArgs> StatisticsUpdated; #endregion #region Properties /// <summary> /// Gets or sets the attribute source. /// </summary> public IAttributeSource AttributeSource { get { return _source; } set { _source = value; UpdateBins(); } } /// <summary> /// Gets or sets the border style for this control. /// </summary> public BorderStyle BorderStyle { get; set; } /// <summary> /// Gets or sets the color to use for the moveable breaks. /// </summary> public Color BreakColor { get { return _breakColor; } set { _breakColor = value; if (Breaks == null) return; foreach (BreakSlider slider in Breaks) { slider.Color = value; } } } /// <summary> /// Gets the list of breaks that are currently part of this graph. /// </summary> public List<BreakSlider> Breaks { get; } /// <summary> /// Gets or sets the color to use when a break is selected. /// </summary> public Color BreakSelectedColor { get { return _selectedBreakColor; } set { _selectedBreakColor = value; if (Breaks == null) return; foreach (BreakSlider slider in Breaks) { slider.SelectColor = value; } } } /// <summary> /// Gets or sets the string field name. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Fieldname { get { return _fieldName; } set { _fieldName = value; UpdateBins(); } } /// <summary> /// Gets or sets the font color. /// </summary> [Category("Appearance")] [Description("Gets or sets the color for the axis labels")] public Color FontColor { get { if (_graph != null) return _graph.Font.Color; return Color.Black; } set { if (_graph != null) _graph.Font.Color = value; } } /// <summary> /// Gets or sets the method to use when breaks are calculated or reset. /// </summary> public IntervalMethod IntervalMethod { get { if (_scheme?.EditorSettings == null) return IntervalMethod.EqualInterval; return _scheme.EditorSettings.IntervalMethod; } set { if (_scheme?.EditorSettings == null) return; _scheme.EditorSettings.IntervalMethod = value; UpdateBreaks(); } } /// <summary> /// Gets or sets a value indicating whether or not count values should be drawn with /// heights that are proportional to the logarithm of the count, instead of the count itself. /// </summary> public bool LogY { get { return _graph != null && _graph.LogY; } set { if (_graph != null) { _graph.LogY = value; Invalidate(); } } } /// <summary> /// Gets or sets the maximum sample size to use when calculating statistics. /// The default is 10000. /// </summary> [Category("Behavior")] [Description("Gets or sets the maximum sample size to use when calculating statistics.")] public int MaximumSampleSize { get; set; } /// <summary> /// Gets or sets the minimum height. Very small counts frequently dissappear next to big counts. One strategey is to use a /// minimum height, so that the difference between 0 and 1 is magnified on the columns. /// </summary> public int MinHeight { get { return _graph?.MinHeight ?? 20; } set { if (_graph != null) _graph.MinHeight = value; } } /// <summary> /// Gets or sets the string normalization field. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string NormalizationField { get { return _normalizationField; } set { _normalizationField = value; UpdateBins(); } } /// <summary> /// Gets or sets the number of columns. Setting this will recalculate the bins. /// </summary> [Category("Behavior")] [Description("Gets or sets the number of columns representing the data histogram")] public int NumColumns { get { if (_graph == null) return 0; return _graph.NumColumns; } set { if (_graph == null) return; _graph.NumColumns = value; FillBins(); UpdateBreaks(); Invalidate(); } } /// <summary> /// Gets or sets the raster layer. This will also force this control to use /// the raster for calculations, rather than the dataset. /// </summary> public IRasterLayer RasterLayer { get { return _rasterLayer; } set { _rasterLayer = value; if (value == null) return; _isRaster = true; _raster = _rasterLayer.DataSet; _rasterSymbolizer = _rasterLayer.Symbolizer; ResetExtents(); UpdateBins(); } } /// <summary> /// Gets or sets the scheme that is currently being used to symbolize the values. /// Setting this automatically updates the graph extents to the statistical bounds /// of the scheme. /// </summary> public IFeatureScheme Scheme { get { return _scheme; } set { _scheme = value; _isRaster = false; ResetExtents(); UpdateBreaks(); } } /// <summary> /// Gets or sets a value indicating whether the mean will be shown as a blue dotted line. /// </summary> [Category("Appearance")] [Description("Boolean, if this is true, the mean will be shown as a blue dotted line.")] public bool ShowMean { get { return _graph != null && _graph.ShowMean; } set { if (_graph != null) { _graph.ShowMean = value; Invalidate(); } } } /// <summary> /// Gets or sets a value indicating whether the integral standard deviations from the mean will be drawn /// as red dotted lines. /// </summary> [Category("Appearance")] [Description("Boolean, if this is true, the integral standard deviations from the mean will be drawn as red dotted lines.")] public bool ShowStandardDeviation { get { return _graph != null && _graph.ShowStandardDeviation; } set { if (_graph != null) { _graph.ShowStandardDeviation = value; Invalidate(); } } } /// <summary> /// Gets the statistics that have been currently calculated for this graph. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Statistics Statistics { get { if (_isRaster) { return _statistics; } return _scheme?.Statistics; } } /// <summary> /// Gets or sets the data Table for which the statistics should be applied. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public DataTable Table { get { return _table; } set { _table = value; UpdateBins(); } } /// <summary> /// Gets or sets the title of the graph. /// </summary> [Category("Appearance")] [Description("Gets or sets the title of the graph.")] public string Title { get { return _graph?.Title; } set { if (_graph != null) _graph.Title = value; } } /// <summary> /// Gets or sets the color to use for the graph title. /// </summary> [Category("Appearance")] [Description("Gets or sets the color to use for the graph title.")] public Color TitleColor { get { return _graph?.TitleFont.Color ?? Color.Black; } set { if (_graph != null) _graph.TitleFont.Color = value; } } /// <summary> /// Gets or sets the font to use for the graph title. /// </summary> [Category("Appearance")] [Description("Gets or sets the font to use for the graph title.")] public Font TitleFont { get { return _graph?.TitleFont.GetFont(); } set { _graph?.TitleFont.SetFont(value); } } #endregion #region Methods /// <summary> /// When the mouse wheel event occurs, this forwards the event to this control. /// </summary> /// <param name="delta">The delta.</param> /// <param name="x">The x.</param> public void DoMouseWheel(int delta, float x) { double val = _graph.GetValue(x); if (delta > 0) { _graph.Minimum = _graph.Minimum + ((val - _graph.Minimum) / 2); _graph.Maximum = _graph.Maximum - ((_graph.Maximum - val) / 2); } else { _graph.Minimum = _graph.Minimum - (val - _graph.Minimum); _graph.Maximum = _graph.Maximum + (_graph.Maximum - val); } if (_isRaster) { if (_graph.Minimum < _rasterSymbolizer.Scheme.Statistics.Minimum) _graph.Minimum = _rasterSymbolizer.Scheme.Statistics.Minimum; if (_graph.Maximum > _rasterSymbolizer.Scheme.Statistics.Maximum) _graph.Maximum = _rasterSymbolizer.Scheme.Statistics.Maximum; } else { if (_graph.Minimum < _scheme.Statistics.Minimum) _graph.Minimum = _scheme.Statistics.Minimum; if (_graph.Maximum > _scheme.Statistics.Maximum) _graph.Maximum = _scheme.Statistics.Maximum; } FillBins(); UpdateBreaks(); Invalidate(); } /// <summary> /// Returns the BreakSlider that corresponds to the specified mouse position, where /// the actual handle and divider represent the maximum of that range. /// </summary> /// <param name="location">The location, which can be anywhere to the left of the slider but to the /// right of any other sliders.</param> /// <returns>The BreakSlider that covers the range that contains the location, or null.</returns> public BreakSlider GetBreakAt(Point location) { if (location.X < 0) return null; foreach (BreakSlider slider in Breaks) { if (slider.Position < location.X) continue; return slider; } return null; } /// <summary> /// Resets the breaks using the current settings, and generates a new set of /// categories using the given interval method. /// </summary> /// <param name="handler">The progress handler.</param> public void ResetBreaks(ICancelProgressHandler handler) { if (_fieldName == null) return; if (_scheme?.EditorSettings == null) return; if (_source != null) { _scheme.CreateCategories(_source, handler); } else { if (_table == null) return; _scheme.CreateCategories(_table); } ResetZoom(); } /// <summary> /// Given a scheme, this resets the graph extents to the statistical bounds. /// </summary> public void ResetExtents() { if (_graph == null) return; Statistics stats; if (_isRaster) { if (_raster == null) return; stats = _rasterSymbolizer.Scheme.Statistics; } else { if (_scheme == null) return; stats = _scheme.Statistics; } _graph.Minimum = stats.Minimum; _graph.Maximum = stats.Maximum; _graph.Mean = stats.Mean; _graph.StandardDeviation = stats.StandardDeviation; } /// <summary> /// Selects one of the specific breaks. /// </summary> /// <param name="slider">The break slider.</param> public void SelectBreak(BreakSlider slider) { if (_selectedSlider != null) _selectedSlider.Selected = false; _selectedSlider = slider; if (_selectedSlider != null) { _selectedSlider.Selected = true; _graph.SelectedRange = _selectedSlider.Range; } } /// <summary> /// Given a scheme, this will build the break list to match approximately. This does not /// force the interval method to build a new scheme. /// </summary> public void UpdateBreaks() { if (_isRaster) { UpdateRasterBreaks(); return; } if (_scheme == null) return; IFeatureCategory selectedCat = null; if (_selectedSlider != null) selectedCat = _selectedSlider.Category as IFeatureCategory; Breaks.Clear(); Statistics stats = _scheme.Statistics; Rectangle gb = _graph.GetGraphBounds(); _graph.ColorRanges.Clear(); foreach (IFeatureCategory category in _scheme.GetCategories()) { ColorRange cr = new ColorRange(category.GetColor(), category.Range); _graph.ColorRanges.Add(cr); BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr) { Color = _breakColor, SelectColor = _selectedBreakColor }; if (selectedCat != null && category == selectedCat) { bs.Selected = true; _selectedSlider = bs; _graph.SelectedRange = cr; } bs.Value = category.Maximum != null ? double.Parse(category.Maximum.ToString()) : stats.Maximum; bs.Category = category; Breaks.Add(bs); } Breaks.Sort(); // Moving a break generally affects both a maximum and a minimum. // Point to the next category to actuate that. for (int i = 0; i < Breaks.Count - 1; i++) { Breaks[i].NextCategory = Breaks[i + 1].Category; // We use the maximums to set up breaks. Minimums should simply // be set to work with the maximums of the previous category. Breaks[i + 1].Category.Minimum = Breaks[i].Value; } if (Breaks.Count == 0) return; int breakIndex = 0; BreakSlider nextSlider = Breaks[breakIndex]; int count = 0; if (_graph?.Bins == null) return; foreach (double value in _values) { if (value < nextSlider.Value) { count++; continue; } nextSlider.Count = count; while (value > nextSlider.Value) { breakIndex++; if (breakIndex >= Breaks.Count) { break; } nextSlider = Breaks[breakIndex]; } count = 0; } } /// <summary> /// Given a break slider's new position, this will update the category related to that break. /// </summary> /// <param name="slider">The break slider.</param> public void UpdateCategory(BreakSlider slider) { slider.Category.Maximum = slider.Value; slider.Category.ApplyMinMax(_scheme.EditorSettings); int index = Breaks.IndexOf(slider); if (index < 0) return; if (index < Breaks.Count - 1) { Breaks[index + 1].Category.Minimum = slider.Value; Breaks[index + 1].Category.ApplyMinMax(_scheme.EditorSettings); } } /// <summary> /// Updates the raster breaks. /// </summary> public void UpdateRasterBreaks() { if (_rasterLayer == null) return; IColorCategory selectedBrk = null; if (_selectedSlider != null) selectedBrk = _selectedSlider.Category as IColorCategory; Breaks.Clear(); Statistics stats = _rasterSymbolizer.Scheme.Statistics; Rectangle gb = _graph.GetGraphBounds(); _graph.ColorRanges.Clear(); foreach (IColorCategory category in _rasterSymbolizer.Scheme.Categories) { ColorRange cr = new ColorRange(category.LowColor, category.Range); _graph.ColorRanges.Add(cr); BreakSlider bs = new BreakSlider(gb, _graph.Minimum, _graph.Maximum, cr) { Color = _breakColor, SelectColor = _selectedBreakColor }; if (selectedBrk != null && category == selectedBrk) { bs.Selected = true; _selectedSlider = bs; _graph.SelectedRange = cr; } bs.Value = category.Maximum != null ? double.Parse(category.Maximum.ToString()) : stats.Maximum; bs.Category = category; Breaks.Add(bs); } Breaks.Sort(); // Moving a break generally affects both a maximum and a minimum. // Point to the next category to actuate that. for (int i = 0; i < Breaks.Count - 1; i++) { Breaks[i].NextCategory = Breaks[i + 1].Category; // We use the maximums to set up breaks. Minimums should simply // be set to work with the maximums of the previous category. // _breaks[i + 1].Category.Minimum = _breaks[i].Value; REMOVED BY jany_ (2015-07-07) Don't set minimum, because that changes the minimum of the rasters category which causes the colors to change when saving in RasterColorControl without making changes or for example only applying opacity without wanting to use statistics. } if (Breaks.Count == 0) return; int breakIndex = 0; BreakSlider nextSlider = Breaks[breakIndex]; int count = 0; if (_graph?.Bins == null) return; foreach (double value in _values) { if (value < nextSlider.Value) { count++; continue; } nextSlider.Count = count; while (value > nextSlider.Value) { breakIndex++; if (breakIndex >= Breaks.Count) { break; } nextSlider = Breaks[breakIndex]; } count = 0; } } /// <summary> /// Zooms so that the minimum is the minimum of the lowest category or else the /// minimum of the extents, and the maximum is the maximum of the largest category /// or else the maximum of the statistics. /// </summary> public void ZoomToCategoryRange() { if (_graph == null) return; Statistics stats; double? min; double? max; if (_isRaster) { if (_raster == null) return; stats = _rasterSymbolizer.Scheme.Statistics; min = _rasterSymbolizer.Scheme.Categories[0].Minimum; max = _rasterSymbolizer.Scheme.Categories[_rasterSymbolizer.Scheme.Categories.Count - 1].Maximum; } else { if (_scheme == null) return; stats = _scheme.Statistics; var cats = _scheme.GetCategories().ToList(); min = cats.First().Minimum; max = cats.Last().Maximum; } _graph.Minimum = (min == null || min.Value < stats.Minimum) ? stats.Minimum : min.Value; _graph.Maximum = (max == null || max.Value > stats.Maximum) ? stats.Maximum : max.Value; FillBins(); UpdateBreaks(); Invalidate(); } /// <summary> /// Handles disposing to release unmanaged memory. /// </summary> /// <param name="disposing">Indicates whether managed resources should be disposed.</param> protected override void Dispose(bool disposing) { _graph?.Dispose(); base.Dispose(disposing); } /// <summary> /// Occurs during drawing. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="clip">The clip rectangle.</param> protected virtual void OnDraw(Graphics g, Rectangle clip) { if (Height <= 1 || Width <= 1) return; // Draw text first because the text is used to auto-fit the remaining graph. _graph.Draw(g, clip); if (BorderStyle == BorderStyle.Fixed3D) { g.DrawLine(Pens.White, 0, Height - 1, Width - 1, Height - 1); g.DrawLine(Pens.White, Width - 1, 0, Width - 1, Height - 1); g.DrawLine(Pens.Gray, 0, 0, 0, Height - 1); g.DrawLine(Pens.Gray, 0, 0, Width - 1, 0); } if (BorderStyle == BorderStyle.FixedSingle) { g.DrawRectangle(Pens.Black, 0, 0, Width - 1, Height - 1); } if (Breaks == null) return; Rectangle gb = _graph.GetGraphBounds(); foreach (BreakSlider slider in Breaks) { slider.Setup(gb, _graph.Minimum, _graph.Maximum); if (slider.Bounds.IntersectsWith(clip)) slider.Draw(g); } } /// <summary> /// Occurs when the mose down occurs. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseDown(MouseEventArgs e) { Focus(); if (e.Button == MouseButtons.Right) { _contextMenu.Show(this, e.Location); return; } foreach (BreakSlider slider in Breaks) { if (!slider.Bounds.Contains(e.Location) && !slider.HandleBounds.Contains(e.Location)) continue; // not sure if this works right. Hopefully, just the little rectangles form a double region. Region rg = new Region(); if (_selectedSlider != null) { rg.Union(_selectedSlider.Bounds); _selectedSlider.Selected = false; } _selectedSlider = slider; slider.Selected = true; rg.Union(_selectedSlider.Bounds); Invalidate(rg); _isDragging = true; OnSliderMoving(); return; } if (_selectedSlider != null) _selectedSlider.Selected = false; _selectedSlider = null; base.OnMouseDown(e); } /// <summary> /// Handles the mouse move event. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseMove(MouseEventArgs e) { if (_isDragging) { Region rg = new Region(); Rectangle gb = _graph.GetGraphBounds(); if (_selectedSlider != null) { rg.Union(_selectedSlider.Bounds); int x = e.X; int index = Breaks.IndexOf(_selectedSlider); if (x > gb.Right) x = gb.Right; if (x < gb.Left) x = gb.Left; if (index > 0) { if (x < Breaks[index - 1].Position + 2) x = (int)Breaks[index - 1].Position + 2; } if (index < Breaks.Count - 1) { if (x > Breaks[index + 1].Position - 2) x = (int)Breaks[index + 1].Position - 2; } _selectedSlider.Position = x; rg.Union(_selectedSlider.Bounds); Invalidate(rg); } return; } bool overSlider = false; foreach (BreakSlider slider in Breaks) { if (slider.Bounds.Contains(e.Location) || slider.HandleBounds.Contains(e.Location)) { overSlider = true; } } if (_dragCursor && !overSlider) { Cursor = Cursors.Arrow; _dragCursor = false; } if (!_dragCursor && overSlider) { _dragCursor = true; Cursor = Cursors.SizeWE; } base.OnMouseMove(e); } /// <summary> /// Handles the mouse up event. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { if (_isDragging) { _isDragging = false; _selectedSlider.Category.Maximum = _selectedSlider.Value; if (_isRaster) { _rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.Category); _selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings); } else { _scheme.ApplySnapping(_selectedSlider.Category); _selectedSlider.Category.ApplyMinMax(_scheme.EditorSettings); } if (_selectedSlider.NextCategory != null) { _selectedSlider.NextCategory.Minimum = _selectedSlider.Value; if (_isRaster) { _rasterSymbolizer.Scheme.ApplySnapping(_selectedSlider.NextCategory); _selectedSlider.Category.ApplyMinMax(_rasterSymbolizer.Scheme.EditorSettings); } else { _scheme.ApplySnapping(_selectedSlider.NextCategory); _selectedSlider.NextCategory.ApplyMinMax(_scheme.EditorSettings); } } OnSliderMoved(); Invalidate(); return; } BreakSlider s = GetBreakAt(e.Location); SelectBreak(s); OnSliderSelected(s); Invalidate(); base.OnMouseUp(e); } /// <summary> /// Custom drawing. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Prevents flicker by preventing the white background being drawn here. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaintBackground(PaintEventArgs e) { // base.OnPaintBackground(pevent); } /// <summary> /// Occurs during a resize. /// </summary> /// <param name="e">The event args.</param> protected override void OnResize(EventArgs e) { _graph.Width = Width; _graph.Height = Height; base.OnResize(e); Invalidate(); } /// <summary> /// Fires the slider moved event. /// </summary> protected virtual void OnSliderMoved() { SliderMoved?.Invoke(this, new BreakSliderEventArgs(_selectedSlider)); } /// <summary> /// Occurs when the slider moves. /// </summary> protected virtual void OnSliderMoving() { SliderMoving?.Invoke(this, new BreakSliderEventArgs(_selectedSlider)); } /// <summary> /// Fires the SliderSelected event. /// </summary> /// <param name="slider">The break slider.</param> protected virtual void OnSliderSelected(BreakSlider slider) { SliderSelected?.Invoke(this, new BreakSliderEventArgs(slider)); } /// <summary> /// Fires the statistics updated event. /// </summary> protected virtual void OnStatisticsUpdated() { StatisticsUpdated?.Invoke(this, new StatisticalEventArgs(_scheme.Statistics)); } private void CategoryZoomClicked(object sender, EventArgs e) { ZoomToCategoryRange(); } private void FillBins() { if (_values == null) return; double min = _graph.Minimum; double max = _graph.Maximum; if (min == max) { min = min - 10; max = max + 10; } double binSize = (max - min) / _graph.NumColumns; int numBins = _graph.NumColumns; int[] bins = new int[numBins]; int maxBinCount = 0; foreach (double val in _values) { if (val < min || val > max) continue; int index = (int)Math.Ceiling((val - min) / binSize); if (index >= numBins) index = numBins - 1; bins[index]++; if (bins[index] > maxBinCount) { maxBinCount = bins[index]; } } _graph.MaxBinCount = maxBinCount; _graph.Bins = bins; } private bool IsValidField(string fieldName) { if (fieldName == null) return false; if (_source != null) return _source.GetColumn(fieldName) != null; return _table != null && _table.Columns.Contains(fieldName); } private void ReadValues() { if (_isRaster) { _values = _raster.GetRandomValues(_rasterSymbolizer.EditorSettings.MaxSampleCount); _statistics.Calculate(_values); if (_values == null) return; return; } _values = _scheme.Values; if (_values == null) return; _scheme.Statistics.Calculate(_values); } private void ResetZoom() { ResetExtents(); FillBins(); UpdateBreaks(); Invalidate(); } private void ResetZoomClicked(object sender, EventArgs e) { ResetZoom(); } private void UpdateBins() { if (_isRaster) { if (_raster == null) return; } else { if (_source == null && _table == null) return; if (!IsValidField(_fieldName)) return; } ReadValues(); FillBins(); UpdateBreaks(); } #endregion } }
using System; using System.Globalization; using System.Linq; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Providers; using Subtext.Framework.Routing; using Subtext.Framework.Services; using Subtext.Framework.Web.HttpModules; using Subtext.Framework.XmlRpc; using Subtext.Infrastructure; using Enclosure = Subtext.Framework.XmlRpc.Enclosure; using FrameworkEnclosure = Subtext.Framework.Components.Enclosure; namespace UnitTests.Subtext.Framework.XmlRpc { [TestFixture] public class MetaBlogApiTests { [Test] public void getCategories_ReturnsCategoriesInRepository() { //arrange var blog = new Blog { AllowServiceAccess = true, Host = "localhost", UserName = "username", Password = "password" }; var category = new LinkCategory { BlogId = blog.Id, IsActive = true, Description = "Test category", Title = "CategoryA", CategoryType = CategoryType.PostCollection, Id = 42 }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.UrlHelper.CategoryUrl(It.IsAny<LinkCategory>())).Returns("/Category/42.aspx"); subtextContext.Setup(c => c.UrlHelper.CategoryRssUrl(It.IsAny<LinkCategory>())).Returns("/rss.aspx?catId=42"); subtextContext.Setup(c => c.Repository.GetCategories(CategoryType.PostCollection, false)).Returns(new[] { category }); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); var api = new MetaWeblog(subtextContext.Object); //act CategoryInfo[] categories = api.getCategories(blog.Id.ToString(), "username", "password"); //assert Assert.AreEqual(1, categories.Length); Assert.AreEqual("http://localhost/Category/42.aspx", categories[0].htmlUrl); Assert.AreEqual("http://localhost/rss.aspx?catId=42", categories[0].rssUrl); } [Test] public void newPost_WithCategory_CreatesEntryWithCategory() { //arrange var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" }; var entryPublisher = new Mock<IEntryPublisher>(); Entry publishedEntry = null; entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); var post = new Post { categories = new[] { "CategoryA" }, description = "A unit test", title = "A unit testing title", dateCreated = DateTime.UtcNow }; //act api.newPost("42", "username", "password", post, true); //assert Assert.IsNotNull(publishedEntry); Assert.AreEqual(1, publishedEntry.Categories.Count); Assert.AreEqual("CategoryA", publishedEntry.Categories.First()); } [Test] public void NewPost_WithNullCategories_DoesNotTHrowException() { //arrange var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); Entry publishedEntry = null; var entryPublisher = new Mock<IEntryPublisher>(); entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>( entry => publishedEntry = entry); var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); var post = new Post { categories = null, description = "A unit test", title = "A unit testing title", dateCreated = DateTime.UtcNow }; // act string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post, true); // assert int entryId = int.Parse(result); Assert.AreEqual(42, entryId); Assert.AreEqual(0, publishedEntry.Categories.Count, "Should not have added categories."); } [Test] public void NewPost_WithFutureDate_SyndicatesInTheFuture() { //arrange var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); Entry publishedEntry = null; var entryPublisher = new Mock<IEntryPublisher>(); entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>( entry => publishedEntry = entry); DateTime now = DateTime.Now; DateTime utcNow = now.ToUniversalTime(); var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); var post = new Post(); post.categories = null; post.description = "A unit test"; post.title = "A unit testing title"; post.dateCreated = utcNow.AddDays(1); // act string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post, true); // assert Assert.IsNotNull(publishedEntry); Assert.Greater(publishedEntry.DateSyndicated, now.AddDays(.75)); Assert.LowerEqualThan(publishedEntry.DateSyndicated, now.AddDays(1)); } [Test] public void NewPostWithEnclosureCreatesEntryWithEnclosure() { //arrange var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); FrameworkEnclosure publishedEnclosure = null; subtextContext.Setup(c => c.Repository.Create(It.IsAny<FrameworkEnclosure>())).Callback<FrameworkEnclosure>( enclosure => publishedEnclosure = enclosure); var entryPublisher = new Mock<IEntryPublisher>(); entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42); DateTime now = DateTime.Now; DateTime utcNow = now.ToUniversalTime(); var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); var post = new Post(); post.categories = null; post.description = "A unit test"; post.title = "A unit testing title"; post.dateCreated = utcNow.AddDays(1); var postEnclosure = new Enclosure(); postEnclosure.url = "http://codeclimber.net.nz/podcast/mypodcast.mp3"; postEnclosure.type = "audio/mp3"; postEnclosure.length = 123456789; post.enclosure = postEnclosure; // act string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post, true); // assert Assert.IsNotNull(publishedEnclosure); Assert.AreEqual("http://codeclimber.net.nz/podcast/mypodcast.mp3", publishedEnclosure.Url); Assert.AreEqual("audio/mp3", publishedEnclosure.MimeType); Assert.AreEqual(123456789, publishedEnclosure.Size); } [Test] public void NewPostAcceptsNullEnclosure() { //arrange var blog = new Blog { Id = 42, UserName = "username", Password = "password", AllowServiceAccess = true, Host = "localhost" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); Entry publishedEntry = null; var entryPublisher = new Mock<IEntryPublisher>(); entryPublisher.Setup(publisher => publisher.Publish(It.IsAny<Entry>())).Returns(42).Callback<Entry>( entry => publishedEntry = entry); DateTime now = DateTime.Now; DateTime utcNow = now.ToUniversalTime(); var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); var post = new Post(); post.categories = null; post.description = "A unit test"; post.title = "A unit testing title"; post.dateCreated = utcNow.AddDays(1); post.enclosure = null; // act string result = api.newPost(blog.Id.ToString(CultureInfo.InvariantCulture), "username", "password", post, true); // assert Assert.IsNull(publishedEntry.Enclosure); } [Test] public void editPost_WithEntryHavingEnclosure_UpdatesEntryEnclosureWithNewEncoluser() { //arrange var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true }; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add("TestCategory"); var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry); var entryPublisher = new Mock<IEntryPublisher>(); Entry publishedEntry = null; entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e); FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", "http://perseus.franklins.net/hanselminutes_0107.mp3", "audio/mp3", 123, 26707573, true, true); entry.Enclosure = enclosure; var post = new Post {title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow}; var postEnclosure = new Enclosure { url = "http://codeclimber.net.nz/podcast/mypodcastUpdated.mp3", type = "audio/mp3", length = 123456789 }; post.enclosure = postEnclosure; var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object); // act bool result = metaWeblog.editPost("123", "username", "password", post, true); // assert Assert.IsTrue(result); Assert.IsNotNull(publishedEntry.Enclosure); Assert.AreEqual("http://codeclimber.net.nz/podcast/mypodcastUpdated.mp3", entry.Enclosure.Url); } [Test] public void editPost_WithEnclosure_AddsNewEnclosure() { //arrange FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", "http://example.com/foo.mp3", "audio/mp3", 123, 26707573, true, true); var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true, Enclosure = enclosure}; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add("TestCategory"); var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry); var entryPublisher = new Mock<IEntryPublisher>(); Entry publishedEntry = null; entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e); var post = new Post { title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow }; var postEnclosure = new Enclosure { url = "http://example.com/bar.mp3", type = "audio/mp3", length = 123456789 }; post.enclosure = postEnclosure; var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object); // act bool result = metaWeblog.editPost("123", "username", "password", post, true); // assert Assert.IsNotNull(publishedEntry.Enclosure); Assert.AreEqual("http://example.com/bar.mp3", entry.Enclosure.Url); Assert.AreEqual("audio/mp3", entry.Enclosure.MimeType); Assert.AreEqual(123456789, entry.Enclosure.Size); Assert.IsTrue(result); } [Test] public void EditPost_WithoutEnclosure_RemovesEnclosureFromEntry() { // arrange FrameworkEnclosure enclosure = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", "http://example.com/foo.mp3", "audio/mp3", 123, 2650, true, true); enclosure.Id = 321; var entry = new Entry(PostType.BlogPost) {Title = "Title 1", Body = "Blah", IsActive = true, Enclosure = enclosure}; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var subtextContext = new Mock<ISubtextContext>(); var blog = new Blog { Id = 999, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" }; subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry); bool enclosureDeleted = false; subtextContext.Setup(c => c.Repository.DeleteEnclosure(321)).Callback(() => enclosureDeleted = true); var entryPublisher = new Mock<IEntryPublisher>(); entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())); var post = new Post {title = "Title 2", description = "Blah", dateCreated = DateTime.UtcNow}; var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); // act bool result = api.editPost("999", "username", "password", post, true); // assert Assert.IsTrue(enclosureDeleted); Assert.IsTrue(result); } [Test] [RollBack] public void editPost_WithPostHavingDifferentCategoryThanEntry_UpdatesCategory() { // arrange var entry = new Entry(PostType.BlogPost) {Id = 12345, Title = "Title 1", Body = "Blah", IsActive = true }; entry.Categories.Add("Category1"); entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var subtextContext = new Mock<ISubtextContext>(); var blog = new Blog { Id = 999, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" }; subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry); var entryPublisher = new Mock<IEntryPublisher>(); Entry publishedEntry = null; entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e); var post = new Post { title = "Title 2", description = "Blah", categories = new[] { "Category2"}, dateCreated = DateTime.UtcNow }; var api = new MetaWeblog(subtextContext.Object, entryPublisher.Object); // act bool result = api.editPost("12345", "username", "password", post, true); // assert Assert.AreEqual(1, publishedEntry.Categories.Count); Assert.AreEqual("Category2", publishedEntry.Categories.First()); Assert.IsTrue(result); } [Test] public void editPost_WithNoCategories_RemovesCategoriesFromEntry() { //arrange var entry = new Entry(PostType.BlogPost) { Title = "Title 1", Body = "Blah", IsActive = true }; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add("TestCategory"); var blog = new Blog { Id = 123, Host = "localhost", AllowServiceAccess = true, UserName = "username", Password = "password" }; var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(blog); subtextContext.Setup(c => c.Repository.GetEntry(It.IsAny<Int32>(), false, true)).Returns(entry); var entryPublisher = new Mock<IEntryPublisher>(); Entry publishedEntry = null; entryPublisher.Setup(p => p.Publish(It.IsAny<Entry>())).Callback<Entry>(e => publishedEntry = e); var post = new Post { title = "Title 2", description = "Blah", categories = null, dateCreated = DateTime.UtcNow }; var metaWeblog = new MetaWeblog(subtextContext.Object, entryPublisher.Object); // act metaWeblog.editPost("123", "username", "password", post, true); // assert Assert.AreEqual(0, publishedEntry.Categories.Count, "We expected no category."); } [Test] [RollBack] public void GetRecentPosts_ReturnsRecentPosts() { string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, ""); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, ""); Blog blog = Config.GetBlog(hostname, ""); BlogRequest.Current.Blog = blog; blog.AllowServiceAccess = true; var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever"); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); //TODO: FIX!!! subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); subtextContext.SetupBlog(blog); subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); var api = new MetaWeblog(subtextContext.Object); Post[] posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10); Assert.AreEqual(0, posts.Length); string category1Name = UnitTestHelper.GenerateUniqueString(); string category2Name = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name); var entry = new Entry(PostType.BlogPost); entry.Title = "Title 1"; entry.Body = "Blah"; entry.IsActive = true; entry.IncludeInMainSyndication = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category1Name); UnitTestHelper.Create(entry); entry = new Entry(PostType.BlogPost); entry.IncludeInMainSyndication = true; entry.Title = "Title 2"; entry.Body = "Blah1"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1976/05/25", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category1Name); entry.Categories.Add(category2Name); UnitTestHelper.Create(entry); entry = new Entry(PostType.BlogPost); entry.Title = "Title 3"; entry.IncludeInMainSyndication = true; entry.Body = "Blah2"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1979/09/16", "yyyy/MM/dd", CultureInfo.InvariantCulture); UnitTestHelper.Create(entry); entry = new Entry(PostType.BlogPost); entry.Title = "Title 4"; entry.IncludeInMainSyndication = true; entry.Body = "Blah3"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("2006/01/01", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category2Name); int entryId = UnitTestHelper.Create(entry); string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3"; string enclosureMimeType = "audio/mp3"; long enclosureSize = 26707573; FrameworkEnclosure enc = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true); Enclosures.Create(enc); posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10); Assert.AreEqual(4, posts.Length, "Expected 4 posts"); Assert.AreEqual(1, posts[3].categories.Length, "Expected our categories to be there."); Assert.AreEqual(2, posts[2].categories.Length, "Expected our categories to be there."); Assert.IsNotNull(posts[1].categories, "Expected our categories to be there."); Assert.AreEqual(1, posts[0].categories.Length, "Expected our categories to be there."); Assert.AreEqual(category1Name, posts[3].categories[0], "The category returned by the MetaBlogApi is wrong."); Assert.AreEqual(category2Name, posts[0].categories[0], "The category returned by the MetaBlogApi is wrong."); Assert.AreEqual(enclosureUrl, posts[0].enclosure.Value.url, "Not what we expected for the enclosure url."); Assert.AreEqual(enclosureMimeType, posts[0].enclosure.Value.type, "Not what we expected for the enclosure mimetype."); Assert.AreEqual(enclosureSize, posts[0].enclosure.Value.length, "Not what we expected for the enclosure size."); } [Test] [RollBack] public void GetPages_WithNumberOfPosts_ReturnsPostsInPages() { //arrange string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, ""); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, ""); BlogRequest.Current.Blog = Config.GetBlog(hostname, ""); Config.CurrentBlog.AllowServiceAccess = true; var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever"); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); //TODO: FIX!!! subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object); var api = new MetaWeblog(subtextContext.Object); Post[] posts = api.getRecentPosts(Config.CurrentBlog.Id.ToString(), "username", "password", 10); Assert.AreEqual(0, posts.Length); string category1Name = UnitTestHelper.GenerateUniqueString(); string category2Name = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name); var entry = new Entry(PostType.Story); entry.Title = "Title 1"; entry.Body = "Blah"; entry.IsActive = true; entry.IncludeInMainSyndication = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); UnitTestHelper.Create(entry); entry = new Entry(PostType.Story); entry.IncludeInMainSyndication = true; entry.Title = "Title 2"; entry.Body = "Blah1"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1976/05/25", "yyyy/MM/dd", CultureInfo.InvariantCulture); UnitTestHelper.Create(entry); entry = new Entry(PostType.Story); entry.Categories.Add(category1Name); entry.Categories.Add(category2Name); entry.Title = "Title 3"; entry.IncludeInMainSyndication = true; entry.Body = "Blah2"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1979/09/16", "yyyy/MM/dd", CultureInfo.InvariantCulture); UnitTestHelper.Create(entry); entry = new Entry(PostType.Story); entry.Title = "Title 4"; entry.IncludeInMainSyndication = true; entry.Body = "Blah3"; entry.IsActive = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("2006/01/01", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category2Name); int entryId = UnitTestHelper.Create(entry); string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3"; string enclosureMimeType = "audio/mp3"; long enclosureSize = 26707573; FrameworkEnclosure enc = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true); Enclosures.Create(enc); //act posts = api.getPages(Config.CurrentBlog.Id.ToString(), "username", "password", 2); //assert Assert.AreEqual(2, posts.Length); Assert.AreEqual(1, posts[0].categories.Length); Assert.AreEqual(2, posts[1].categories.Length); Assert.IsNotNull(posts[1].categories, "Expected our categories to be there."); Assert.AreEqual(enclosureUrl, posts[0].enclosure.Value.url); Assert.AreEqual(enclosureMimeType, posts[0].enclosure.Value.type); Assert.AreEqual(enclosureSize, posts[0].enclosure.Value.length); } [Test] [RollBack] public void GetPost_WithEntryId_ReturnsPostWithCorrectEntryUrl() { //arrange string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, ""); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, ""); BlogRequest.Current.Blog = Config.GetBlog(hostname, ""); Config.CurrentBlog.AllowServiceAccess = true; var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever"); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); //TODO: FIX!!! subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object); var api = new MetaWeblog(subtextContext.Object); string category1Name = UnitTestHelper.GenerateUniqueString(); string category2Name = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name); var entry = new Entry(PostType.BlogPost); entry.Title = "Title 1"; entry.Body = "Blah"; entry.IsActive = true; entry.IncludeInMainSyndication = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category1Name); int entryId = UnitTestHelper.Create(entry); string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3"; string enclosureMimeType = "audio/mp3"; long enclosureSize = 26707573; FrameworkEnclosure enc = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true); Enclosures.Create(enc); //act Post post = api.getPost(entryId.ToString(), "username", "password"); //assert Assert.AreEqual(1, post.categories.Length); Assert.AreEqual("http://" + hostname + "/entry/whatever", post.link); Assert.AreEqual("http://" + hostname + "/entry/whatever", post.permalink); Assert.AreEqual(category1Name, post.categories[0]); Assert.AreEqual(enclosureUrl, post.enclosure.Value.url); Assert.AreEqual(enclosureMimeType, post.enclosure.Value.type); Assert.AreEqual(enclosureSize, post.enclosure.Value.length); } [Test] [RollBack] public void GetPage_ReturnsPostWithhCorrectEntrUrl() { //arrange string hostname = UnitTestHelper.GenerateUniqueString(); Config.CreateBlog("", "username", "password", hostname, ""); UnitTestHelper.SetHttpContextWithBlogRequest(hostname, ""); BlogRequest.Current.Blog = Config.GetBlog(hostname, ""); Config.CurrentBlog.AllowServiceAccess = true; var urlHelper = new Mock<UrlHelper>(); urlHelper.Setup(u => u.EntryUrl(It.IsAny<Entry>())).Returns("/entry/whatever"); var subtextContext = new Mock<ISubtextContext>(); subtextContext.Setup(c => c.Blog).Returns(Config.CurrentBlog); //TODO: FIX!!! subtextContext.Setup(c => c.Repository).Returns(ObjectProvider.Instance()); subtextContext.Setup(c => c.ServiceLocator).Returns(new Mock<IServiceLocator>().Object); subtextContext.Setup(c => c.UrlHelper).Returns(urlHelper.Object); var api = new MetaWeblog(subtextContext.Object); string category1Name = UnitTestHelper.GenerateUniqueString(); string category2Name = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category1Name); UnitTestHelper.CreateCategory(Config.CurrentBlog.Id, category2Name); var entry = new Entry(PostType.Story); entry.Title = "Title 1"; entry.Body = "Blah"; entry.IsActive = true; entry.IncludeInMainSyndication = true; entry.DateCreated = entry.DateSyndicated = entry.DateModified = DateTime.ParseExact("1975/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); entry.Categories.Add(category1Name); int entryId = UnitTestHelper.Create(entry); string enclosureUrl = "http://perseus.franklins.net/hanselminutes_0107.mp3"; string enclosureMimeType = "audio/mp3"; long enclosureSize = 26707573; FrameworkEnclosure enc = UnitTestHelper.BuildEnclosure("<Digital Photography Explained (for Geeks) with Aaron Hockley/>", enclosureUrl, enclosureMimeType, entryId, enclosureSize, true, true); Enclosures.Create(enc); //act Post post = api.getPage(Config.CurrentBlog.Id.ToString(), entryId.ToString(), "username", "password"); //assert Assert.AreEqual(1, post.categories.Length); Assert.AreEqual("http://" + hostname + "/entry/whatever", post.link); Assert.AreEqual("http://" + hostname + "/entry/whatever", post.permalink); Assert.AreEqual(category1Name, post.categories[0]); Assert.AreEqual(enclosureUrl, post.enclosure.Value.url); Assert.AreEqual(enclosureMimeType, post.enclosure.Value.type); Assert.AreEqual(enclosureSize, post.enclosure.Value.length); } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- // ForestEditorGui Script Methods function ForestEditorGui::setActiveTool( %this, %tool ) { if ( %tool == ForestTools->BrushTool ) ForestEditTabBook.selectPage(0); Parent::setActiveTool( %this, %tool ); } /// This is called by the editor when the active forest has /// changed giving us a chance to update the GUI. function ForestEditorGui::onActiveForestUpdated( %this, %forest, %createNew ) { %gotForest = isObject( %forest ); // Give the user a chance to add a forest. if ( !%gotForest && %createNew ) { MessageBoxYesNo( "Forest", "There is not a Forest in this mission. Do you want to add one?", %this @ ".createForest();", "" ); return; } } /// Called from a message box when a forest is not found. function ForestEditorGui::createForest( %this ) { if ( isObject( theForest ) ) { error( "Cannot create a second 'theForest' Forest!" ); return; } // Allocate the Forest and make it undoable. new Forest( theForest ) { dataFile = ""; parentGroup = "MissionGroup"; }; MECreateUndoAction::submit( theForest ); ForestEditorInspector.inspect( theForest ); EWorldEditor.isDirty = true; } function ForestEditorGui::newBrush( %this ) { %internalName = getUniqueInternalName( "Brush", ForestBrushGroup, true ); %brush = new ForestBrush() { internalName = %internalName; parentGroup = ForestBrushGroup; }; MECreateUndoAction::submit( %brush ); ForestEditBrushTree.open( ForestBrushGroup ); ForestEditBrushTree.buildVisibleTree(true); %item = ForestEditBrushTree.findItemByObjectId( %brush ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.addSelection( %item ); ForestEditBrushTree.scrollVisible( %item ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::newElement( %this ) { %sel = ForestEditBrushTree.getSelectedObject(); if ( !isObject( %sel ) ) %parentGroup = ForestBrushGroup; else { if ( %sel.getClassName() $= "ForestBrushElement" ) %parentGroup = %sel.parentGroup; else %parentGroup = %sel; } %internalName = getUniqueInternalName( "Element", ForestBrushGroup, true ); %element = new ForestBrushElement() { internalName = %internalName; parentGroup = %parentGroup; }; MECreateUndoAction::submit( %element ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element.getId() ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::deleteBrushOrElement( %this ) { ForestEditBrushTree.deleteSelection(); ForestEditorPlugin.dirty = true; } function ForestEditorGui::newMesh( %this ) { %spec = "All Mesh Files|*.dts;*.dae|DTS|*.dts|DAE|*.dae"; %dlg = new OpenFileDialog() { Filters = %spec; DefaultPath = $Pref::WorldEditor::LastPath; DefaultFile = ""; ChangePath = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::WorldEditor::LastPath = filePath( %dlg.FileName ); %fullPath = makeRelativePath( %dlg.FileName, getMainDotCSDir() ); %file = fileBase( %fullPath ); } %dlg.delete(); if ( !%ret ) return; %name = getUniqueName( %file ); %str = "datablock TSForestItemData( " @ %name @ " ) { shapeFile = \"" @ %fullPath @ "\"; };"; eval( %str ); if ( isObject( %name ) ) { ForestEditMeshTree.clearSelection(); ForestEditMeshTree.buildVisibleTree( true ); %item = ForestEditMeshTree.findItemByObjectId( %name.getId() ); ForestEditMeshTree.scrollVisible( %item ); ForestEditMeshTree.addSelection( %item ); ForestDataManager.setDirty( %name, "art/forest/managedItemData.cs" ); %element = new ForestBrushElement() { internalName = %name; forestItemData = %name; parentGroup = ForestBrushGroup; }; ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element.getId() ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); pushInstantGroup(); %action = new MECreateUndoAction() { actionName = "Create TSForestItemData"; }; popInstantGroup(); %action.addObject( %name ); %action.addObject( %element ); %action.addToManager( Editor.getUndoManager() ); ForestEditorPlugin.dirty = true; } } function ForestEditorGui::deleteMesh( %this ) { %obj = ForestEditMeshTree.getSelectedObject(); // Can't delete itemData's that are in use without // crashing at the moment... if ( isObject( %obj ) ) { MessageBoxOKCancel( "Warning", "Deleting this mesh will also delete BrushesElements and ForestItems referencing it.", "ForestEditorGui.okDeleteMesh(" @ %obj @ ");", "" ); } } function ForestEditorGui::okDeleteMesh( %this, %mesh ) { // Remove mesh from file ForestDataManager.removeObjectFromFile( %mesh, "art/forest/managedItemData.cs" ); // Submitting undo actions is handled in code. %this.deleteMeshSafe( %mesh ); // Update TreeViews. ForestEditBrushTree.buildVisibleTree( true ); ForestEditMeshTree.buildVisibleTree( true ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::validateBrushSize( %this ) { %minBrushSize = 1; %maxBrushSize = getWord(ETerrainEditor.maxBrushSize, 0); %val = $ThisControl.getText(); if(%val < %minBrushSize) $ThisControl.setValue(%minBrushSize); else if(%val > %maxBrushSize) $ThisControl.setValue(%maxBrushSize); } // Child-control Script Methods function ForestEditMeshTree::onSelect( %this, %obj ) { ForestEditorInspector.inspect( %obj ); } function ForestEditBrushTree::onRemoveSelection( %this, %obj ) { %this.buildVisibleTree( true ); ForestTools->BrushTool.collectElements(); if ( %this.getSelectedItemsCount() == 1 ) ForestEditorInspector.inspect( %obj ); else ForestEditorInspector.inspect( "" ); } function ForestEditBrushTree::onAddSelection( %this, %obj ) { %this.buildVisibleTree( true ); ForestTools->BrushTool.collectElements(); if ( %this.getSelectedItemsCount() == 1 ) ForestEditorInspector.inspect( %obj ); else ForestEditorInspector.inspect( "" ); } function ForestEditTabBook::onTabSelected( %this, %text, %idx ) { %bbg = ForestEditorPalleteWindow.findObjectByInternalName("BrushButtonGroup"); %mbg = ForestEditorPalleteWindow.findObjectByInternalName("MeshButtonGroup"); %bbg.setVisible( false ); %mbg.setVisible( false ); if ( %text $= "Brushes" ) { %bbg.setVisible( true ); %obj = ForestEditBrushTree.getSelectedObject(); ForestEditorInspector.inspect( %obj ); } else if ( %text $= "Meshes" ) { %mbg.setVisible( true ); %obj = ForestEditMeshTree.getSelectedObject(); ForestEditorInspector.inspect( %obj ); } } function ForestEditBrushTree::onDeleteSelection( %this ) { %list = ForestEditBrushTree.getSelectedObjectList(); MEDeleteUndoAction::submit( %list, true ); ForestEditorPlugin.dirty = true; } function ForestEditBrushTree::onDragDropped( %this ) { ForestEditorPlugin.dirty = true; } function ForestEditMeshTree::onDragDropped( %this ) { ForestEditorPlugin.dirty = true; } function ForestEditMeshTree::onDeleteObject( %this, %obj ) { // return true - skip delete. return true; } function ForestEditMeshTree::onDoubleClick( %this ) { %obj = %this.getSelectedObject(); %name = getUniqueInternalName( %obj.getName(), ForestBrushGroup, true ); %element = new ForestBrushElement() { internalName = %name; forestItemData = %obj.getName(); parentGroup = ForestBrushGroup; }; //ForestDataManager.setDirty( %element, "art/forest/brushes.cs" ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); ForestEditorPlugin.dirty = true; } function ForestEditBrushTree::handleRenameObject( %this, %name, %obj ) { if ( %name !$= "" ) { %found = ForestBrushGroup.findObjectByInternalName( %name ); if ( isObject( %found ) && %found.getId() != %obj.getId() ) { MessageBoxOK( "Error", "Brush or Element with that name already exists.", "" ); // true as in, we handled it, don't rename the object. return true; } } // Since we aren't showing any groups whens inspecting a ForestBrushGroup // we can't push this event off to the inspector to handle. //return GuiTreeViewCtrl::handleRenameObject( %this, %name, %obj ); // The instant group will try to add our // UndoAction if we don't disable it. pushInstantGroup(); %nameOrClass = %obj.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %obj.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ "internalName" @ " Change"; objectId = %obj.getId(); fieldName = "internalName"; fieldValue = %obj.internalName; arrayIndex = 0; inspectorGui = ""; }; // Restore the instant group. popInstantGroup(); %action.addToManager( Editor.getUndoManager() ); EWorldEditor.isDirty = true; return false; } function ForestEditorInspector::inspect( %this, %obj ) { if ( isObject( %obj ) ) %class = %obj.getClassName(); %this.showObjectName = false; %this.showCustomFields = false; switch$ ( %class ) { case "ForestBrush": %this.groupFilters = "+NOTHING,-Ungrouped"; case "ForestBrushElement": %this.groupFilters = "+ForestBrushElement,-Ungrouped"; case "TSForestItemData": %this.groupFilters = "+Media,+Wind"; default: %this.groupFilters = ""; } Parent::inspect( %this, %obj ); } function ForestEditorInspector::onInspectorFieldModified( %this, %object, %fieldName, %oldValue, %newValue ) { // The instant group will try to add our // UndoAction if we don't disable it. %instantGroup = $InstantGroup; $InstantGroup = 0; %nameOrClass = %object.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %oldValue; inspectorGui = %this; }; // Restore the instant group. $InstantGroup = %instantGroup; %action.addToManager( Editor.getUndoManager() ); if ( %object.getClassName() $= "TSForestItemData" ) ForestDataManager.setDirty( %object ); ForestEditorPlugin.dirty = true; } function ForestEditorInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) { //FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc ); } function ForestBrushSizeSliderCtrlContainer::onWake(%this) { %this-->slider.range = "1" SPC getWord(ETerrainEditor.maxBrushSize, 0); %this-->slider.setValue(ForestBrushSizeTextEditContainer-->textEdit.getValue()); }
// 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.Collections.Generic; namespace System.Xml.Serialization { /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class XmlElementAttributes : IList { private List<XmlElementAttribute> _list = new List<XmlElementAttribute>(); /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlElementAttribute this[int index] { get { return _list[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } _list[index] = value; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Add(XmlElementAttribute value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } int index = _list.Count; _list.Add(value); return index; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Insert(int index, XmlElementAttribute value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } _list.Insert(index, value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int IndexOf(XmlElementAttribute value) { return _list.IndexOf(value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public bool Contains(XmlElementAttribute value) { return _list.Contains(value); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void Remove(XmlElementAttribute value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (!_list.Remove(value)) { throw new ArgumentException(SR.Arg_RemoveArgNotFound); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void CopyTo(XmlElementAttribute[] array, int index) { _list.CopyTo(array, index); } private IList List { get { return _list; } } public int Count { get { return _list == null ? 0 : _list.Count; } } public void Clear() { _list.Clear(); } public void RemoveAt(int index) { _list.RemoveAt(index); } bool IList.IsReadOnly { get { return List.IsReadOnly; } } bool IList.IsFixedSize { get { return List.IsFixedSize; } } bool ICollection.IsSynchronized { get { return List.IsSynchronized; } } Object ICollection.SyncRoot { get { return List.SyncRoot; } } void ICollection.CopyTo(Array array, int index) { List.CopyTo(array, index); } Object IList.this[int index] { get { return List[index]; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } List[index] = value; } } bool IList.Contains(Object value) { return List.Contains(value); } int IList.Add(Object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return List.Add(value); } void IList.Remove(Object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } var attribute = value as XmlElementAttribute; if (attribute == null) { throw new ArgumentException(SR.Arg_RemoveArgNotFound); } Remove(attribute); } int IList.IndexOf(Object value) { return List.IndexOf(value); } void IList.Insert(int index, Object value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } List.Insert(index, value); } public IEnumerator GetEnumerator() { return List.GetEnumerator(); } } }
// 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.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using System.Text; namespace System.Reflection.Internal { [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal unsafe readonly struct MemoryBlock { internal readonly byte* Pointer; internal readonly int Length; internal MemoryBlock(byte* buffer, int length) { Debug.Assert(length >= 0 && (buffer != null || length == 0)); this.Pointer = buffer; this.Length = length; } internal static MemoryBlock CreateChecked(byte* buffer, int length) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length)); } if (buffer == null && length != 0) { throw new ArgumentNullException(nameof(buffer)); } return new MemoryBlock(buffer, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckBounds(int offset, int byteCount) { if (unchecked((ulong)(uint)offset + (uint)byteCount) > (ulong)Length) { Throw.OutOfBounds(); } } internal byte[] ToArray() { return Pointer == null ? null : PeekBytes(0, Length); } private string GetDebuggerDisplay() { if (Pointer == null) { return "<null>"; } int displayedBytes; return GetDebuggerDisplay(out displayedBytes); } internal string GetDebuggerDisplay(out int displayedBytes) { displayedBytes = Math.Min(Length, 64); string result = BitConverter.ToString(PeekBytes(0, displayedBytes)); if (displayedBytes < Length) { result += "-..."; } return result; } internal string GetDebuggerDisplay(int offset) { if (Pointer == null) { return "<null>"; } int displayedBytes; string display = GetDebuggerDisplay(out displayedBytes); if (offset < displayedBytes) { display = display.Insert(offset * 3, "*"); } else if (displayedBytes == Length) { display += "*"; } else { display += "*..."; } return display; } internal MemoryBlock GetMemoryBlockAt(int offset, int length) { CheckBounds(offset, length); return new MemoryBlock(Pointer + offset, length); } internal byte PeekByte(int offset) { CheckBounds(offset, sizeof(byte)); return Pointer[offset]; } internal int PeekInt32(int offset) { uint result = PeekUInt32(offset); if (unchecked((int)result != result)) { Throw.ValueOverflow(); } return (int)result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal uint PeekUInt32(int offset) { CheckBounds(offset, sizeof(uint)); unchecked { byte* ptr = Pointer + offset; return (uint)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)); } } /// <summary> /// Decodes a compressed integer value starting at offset. /// See Metadata Specification section II.23.2: Blobs and signatures. /// </summary> /// <param name="offset">Offset to the start of the compressed data.</param> /// <param name="numberOfBytesRead">Bytes actually read.</param> /// <returns> /// Value between 0 and 0x1fffffff, or <see cref="BlobReader.InvalidCompressedInteger"/> if the value encoding is invalid. /// </returns> internal int PeekCompressedInteger(int offset, out int numberOfBytesRead) { CheckBounds(offset, 0); byte* ptr = Pointer + offset; long limit = Length - offset; if (limit == 0) { numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } byte headerByte = ptr[0]; if ((headerByte & 0x80) == 0) { numberOfBytesRead = 1; return headerByte; } else if ((headerByte & 0x40) == 0) { if (limit >= 2) { numberOfBytesRead = 2; return ((headerByte & 0x3f) << 8) | ptr[1]; } } else if ((headerByte & 0x20) == 0) { if (limit >= 4) { numberOfBytesRead = 4; return ((headerByte & 0x1f) << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3]; } } numberOfBytesRead = 0; return BlobReader.InvalidCompressedInteger; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ushort PeekUInt16(int offset) { CheckBounds(offset, sizeof(ushort)); unchecked { byte* ptr = Pointer + offset; return (ushort)(ptr[0] | (ptr[1] << 8)); } } // When reference has tag bits. internal uint PeekTaggedReference(int offset, bool smallRefSize) { return PeekReferenceUnchecked(offset, smallRefSize); } // Use when searching for a tagged or non-tagged reference. // The result may be an invalid reference and shall only be used to compare with a valid reference. internal uint PeekReferenceUnchecked(int offset, bool smallRefSize) { return smallRefSize ? PeekUInt16(offset) : PeekUInt32(offset); } // When reference has at most 24 bits. internal int PeekReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!TokenTypeIds.IsValidRowId(value)) { Throw.ReferenceOverflow(); } return (int)value; } // #String, #Blob heaps internal int PeekHeapReference(int offset, bool smallRefSize) { if (smallRefSize) { return PeekUInt16(offset); } uint value = PeekUInt32(offset); if (!HeapHandleType.IsValidHeapOffset(value)) { Throw.ReferenceOverflow(); } return (int)value; } internal Guid PeekGuid(int offset) { CheckBounds(offset, sizeof(Guid)); byte* ptr = Pointer + offset; if (BitConverter.IsLittleEndian) { return *(Guid*)ptr; } else { unchecked { return new Guid( (int)(ptr[0] | (ptr[1] << 8) | (ptr[2] << 16) | (ptr[3] << 24)), (short)(ptr[4] | (ptr[5] << 8)), (short)(ptr[6] | (ptr[7] << 8)), ptr[8], ptr[9], ptr[10], ptr[11], ptr[12], ptr[13], ptr[14], ptr[15]); } } } internal string PeekUtf16(int offset, int byteCount) { CheckBounds(offset, byteCount); byte* ptr = Pointer + offset; if (BitConverter.IsLittleEndian) { // doesn't allocate a new string if byteCount == 0 return new string((char*)ptr, 0, byteCount / sizeof(char)); } else { return Encoding.Unicode.GetString(ptr, byteCount); } } internal string PeekUtf8(int offset, int byteCount) { CheckBounds(offset, byteCount); return Encoding.UTF8.GetString(Pointer + offset, byteCount); } /// <summary> /// Read UTF8 at the given offset up to the given terminator, null terminator, or end-of-block. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="prefix">UTF8 encoded prefix to prepend to the bytes at the offset before decoding.</param> /// <param name="utf8Decoder">The UTF8 decoder to use that allows user to adjust fallback and/or reuse existing strings without allocating a new one.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <returns>The decoded string.</returns> internal string PeekUtf8NullTerminated(int offset, byte[] prefix, MetadataStringDecoder utf8Decoder, out int numberOfBytesRead, char terminator = '\0') { Debug.Assert(terminator <= 0x7F); CheckBounds(offset, 0); int length = GetUtf8NullTerminatedLength(offset, out numberOfBytesRead, terminator); return EncodingHelper.DecodeUtf8(Pointer + offset, length, prefix, utf8Decoder); } /// <summary> /// Get number of bytes from offset to given terminator, null terminator, or end-of-block (whichever comes first). /// Returned length does not include the terminator, but numberOfBytesRead out parameter does. /// </summary> /// <param name="offset">Offset in to the block where the UTF8 bytes start.</param> /// <param name="terminator">A character in the ASCII range that marks the end of the string. /// If a value other than '\0' is passed we still stop at the null terminator if encountered first.</param> /// <param name="numberOfBytesRead">The number of bytes read, which includes the terminator if we did not hit the end of the block.</param> /// <returns>Length (byte count) not including terminator.</returns> internal int GetUtf8NullTerminatedLength(int offset, out int numberOfBytesRead, char terminator = '\0') { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7f); byte* start = Pointer + offset; byte* end = Pointer + Length; byte* current = start; while (current < end) { byte b = *current; if (b == 0 || b == terminator) { break; } current++; } int length = (int)(current - start); numberOfBytesRead = length; if (current < end) { // we also read the terminator numberOfBytesRead++; } return length; } internal int Utf8NullTerminatedOffsetOfAsciiChar(int startOffset, char asciiChar) { CheckBounds(startOffset, 0); Debug.Assert(asciiChar != 0 && asciiChar <= 0x7f); for (int i = startOffset; i < Length; i++) { byte b = Pointer[i]; if (b == 0) { break; } if (b == asciiChar) { return i; } } return -1; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedEquals(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int firstDifference; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out firstDifference, terminator, ignoreCase); if (result == FastComparisonResult.Inconclusive) { int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.Equals(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } return result == FastComparisonResult.Equal; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStartsWith(int offset, string text, MetadataStringDecoder utf8Decoder, char terminator, bool ignoreCase) { int endIndex; FastComparisonResult result = Utf8NullTerminatedFastCompare(offset, text, 0, out endIndex, terminator, ignoreCase); switch (result) { case FastComparisonResult.Equal: case FastComparisonResult.BytesStartWithText: return true; case FastComparisonResult.Unequal: case FastComparisonResult.TextStartsWithBytes: return false; default: Debug.Assert(result == FastComparisonResult.Inconclusive); int bytesRead; string decoded = PeekUtf8NullTerminated(offset, null, utf8Decoder, out bytesRead, terminator); return decoded.StartsWith(text, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); } } internal enum FastComparisonResult { Equal, BytesStartWithText, TextStartsWithBytes, Unequal, Inconclusive } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal FastComparisonResult Utf8NullTerminatedFastCompare(int offset, string text, int textStart, out int firstDifferenceIndex, char terminator, bool ignoreCase) { CheckBounds(offset, 0); Debug.Assert(terminator <= 0x7F); byte* startPointer = Pointer + offset; byte* endPointer = Pointer + Length; byte* currentPointer = startPointer; int ignoreCaseMask = StringUtils.IgnoreCaseMask(ignoreCase); int currentIndex = textStart; while (currentIndex < text.Length && currentPointer != endPointer) { byte currentByte = *currentPointer; // note that terminator is not compared case-insensitively even if ignore case is true if (currentByte == 0 || currentByte == terminator) { break; } char currentChar = text[currentIndex]; if ((currentByte & 0x80) == 0 && StringUtils.IsEqualAscii(currentChar, currentByte, ignoreCaseMask)) { currentIndex++; currentPointer++; } else { firstDifferenceIndex = currentIndex; // uncommon non-ascii case --> fall back to slow allocating comparison. return (currentChar > 0x7F) ? FastComparisonResult.Inconclusive : FastComparisonResult.Unequal; } } firstDifferenceIndex = currentIndex; bool textTerminated = currentIndex == text.Length; bool bytesTerminated = currentPointer == endPointer || *currentPointer == 0 || *currentPointer == terminator; if (textTerminated && bytesTerminated) { return FastComparisonResult.Equal; } return textTerminated ? FastComparisonResult.BytesStartWithText : FastComparisonResult.TextStartsWithBytes; } // comparison stops at null terminator, terminator parameter, or end-of-block -- whichever comes first. internal bool Utf8NullTerminatedStringStartsWithAsciiPrefix(int offset, string asciiPrefix) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); // Make sure that we won't read beyond the block even if the block doesn't end with 0 byte. if (asciiPrefix.Length > Length - offset) { return false; } byte* p = Pointer + offset; for (int i = 0; i < asciiPrefix.Length; i++) { Debug.Assert(asciiPrefix[i] > 0 && asciiPrefix[i] <= 0x7f); if (asciiPrefix[i] != *p) { return false; } p++; } return true; } internal int CompareUtf8NullTerminatedStringWithAsciiString(int offset, string asciiString) { // Assumes stringAscii only contains ASCII characters and no nil characters. CheckBounds(offset, 0); byte* p = Pointer + offset; int limit = Length - offset; for (int i = 0; i < asciiString.Length; i++) { Debug.Assert(asciiString[i] > 0 && asciiString[i] <= 0x7f); if (i > limit) { // Heap value is shorter. return -1; } if (*p != asciiString[i]) { // If we hit the end of the heap value (*p == 0) // the heap value is shorter than the string, so we return negative value. return *p - asciiString[i]; } p++; } // Either the heap value name matches exactly the given string or // it is longer so it is considered "greater". return (*p == 0) ? 0 : +1; } internal byte[] PeekBytes(int offset, int byteCount) { CheckBounds(offset, byteCount); return BlobUtilities.ReadBytes(Pointer + offset, byteCount); } internal int IndexOf(byte b, int start) { CheckBounds(start, 0); return IndexOfUnchecked(b, start); } internal int IndexOfUnchecked(byte b, int start) { byte* p = Pointer + start; byte* end = Pointer + Length; while (p < end) { if (*p == b) { return (int)(p - Pointer); } p++; } return -1; } // same as Array.BinarySearch, but without using IComparer internal int BinarySearch(string[] asciiKeys, int offset) { var low = 0; var high = asciiKeys.Length - 1; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = asciiKeys[middle]; int comparison = CompareUtf8NullTerminatedStringWithAsciiString(offset, midValue); if (comparison == 0) { return middle; } if (comparison < 0) { high = middle - 1; } else { low = middle + 1; } } return ~low; } /// <summary> /// In a table that specifies children via a list field (e.g. TypeDef.FieldList, TypeDef.MethodList), /// searches for the parent given a reference to a child. /// </summary> /// <returns>Returns row number [0..RowCount).</returns> internal int BinarySearchForSlot( int rowCount, int rowSize, int referenceListOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; uint startValue = PeekReferenceUnchecked(startRowNumber * rowSize + referenceListOffset, isReferenceSmall); uint endValue = PeekReferenceUnchecked(endRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (endRowNumber == 1) { if (referenceValue >= endValue) { return endRowNumber; } return startRowNumber; } while (endRowNumber - startRowNumber > 1) { if (referenceValue <= startValue) { return referenceValue == startValue ? startRowNumber : startRowNumber - 1; } if (referenceValue >= endValue) { return referenceValue == endValue ? endRowNumber : endRowNumber + 1; } int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceListOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber; startValue = midReferenceValue; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber; endValue = midReferenceValue; } else { return midRowNumber; } } return startRowNumber; } /// <summary> /// In a table ordered by a column containing entity references searches for a row with the specified reference. /// </summary> /// <returns>Returns row number [0..RowCount) or -1 if not found.</returns> internal int BinarySearchReference( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = rowCount - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked(midRowNumber * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } // Row number [0, ptrTable.Length) or -1 if not found. internal int BinarySearchReference( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int startRowNumber = 0; int endRowNumber = ptrTable.Length - 1; while (startRowNumber <= endRowNumber) { int midRowNumber = (startRowNumber + endRowNumber) / 2; uint midReferenceValue = PeekReferenceUnchecked((ptrTable[midRowNumber] - 1) * rowSize + referenceOffset, isReferenceSmall); if (referenceValue > midReferenceValue) { startRowNumber = midRowNumber + 1; } else if (referenceValue < midReferenceValue) { endRowNumber = midRowNumber - 1; } else { return midRowNumber; } } return -1; } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int rowCount, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, rowCount) or -1 out int endRowNumber) // [0, rowCount) or -1 { int foundRowNumber = BinarySearchReference( rowCount, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((startRowNumber - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < rowCount && PeekReferenceUnchecked((endRowNumber + 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } /// <summary> /// Calculates a range of rows that have specified value in the specified column in a table that is sorted by that column. /// </summary> internal void BinarySearchReferenceRange( int[] ptrTable, int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall, out int startRowNumber, // [0, ptrTable.Length) or -1 out int endRowNumber) // [0, ptrTable.Length) or -1 { int foundRowNumber = BinarySearchReference( ptrTable, rowSize, referenceOffset, referenceValue, isReferenceSmall ); if (foundRowNumber == -1) { startRowNumber = -1; endRowNumber = -1; return; } startRowNumber = foundRowNumber; while (startRowNumber > 0 && PeekReferenceUnchecked((ptrTable[startRowNumber - 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { startRowNumber--; } endRowNumber = foundRowNumber; while (endRowNumber + 1 < ptrTable.Length && PeekReferenceUnchecked((ptrTable[endRowNumber + 1] - 1) * rowSize + referenceOffset, isReferenceSmall) == referenceValue) { endRowNumber++; } } // Always RowNumber.... internal int LinearSearchReference( int rowSize, int referenceOffset, uint referenceValue, bool isReferenceSmall) { int currOffset = referenceOffset; int totalSize = this.Length; while (currOffset < totalSize) { uint currReference = PeekReferenceUnchecked(currOffset, isReferenceSmall); if (currReference == referenceValue) { return currOffset / rowSize; } currOffset += rowSize; } return -1; } internal bool IsOrderedByReferenceAscending( int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; uint previous = 0; while (offset < totalSize) { uint current = PeekReferenceUnchecked(offset, isReferenceSmall); if (current < previous) { return false; } previous = current; offset += rowSize; } return true; } internal int[] BuildPtrTable( int numberOfRows, int rowSize, int referenceOffset, bool isReferenceSmall) { int[] ptrTable = new int[numberOfRows]; uint[] unsortedReferences = new uint[numberOfRows]; for (int i = 0; i < ptrTable.Length; i++) { ptrTable[i] = i + 1; } ReadColumn(unsortedReferences, rowSize, referenceOffset, isReferenceSmall); Array.Sort(ptrTable, (int a, int b) => { return unsortedReferences[a - 1].CompareTo(unsortedReferences[b - 1]); }); return ptrTable; } private void ReadColumn( uint[] result, int rowSize, int referenceOffset, bool isReferenceSmall) { int offset = referenceOffset; int totalSize = this.Length; int i = 0; while (offset < totalSize) { result[i] = PeekReferenceUnchecked(offset, isReferenceSmall); offset += rowSize; i++; } Debug.Assert(i == result.Length); } internal bool PeekHeapValueOffsetAndSize(int index, out int offset, out int size) { int bytesRead; int numberOfBytes = PeekCompressedInteger(index, out bytesRead); if (numberOfBytes == BlobReader.InvalidCompressedInteger) { offset = 0; size = 0; return false; } offset = index + bytesRead; size = numberOfBytes; return true; } } }
// Copyright 2010-2021 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Google.OrTools.ConstraintSolver { using System; using System.Collections.Generic; public partial class Solver : IDisposable { public IntVar[] MakeIntVarArray(int count, long min, long max) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(min, max); } return array; } public IntVar[] MakeIntVarArray(int count, long min, long max, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(min, max, var_name); } return array; } public IntVar[] MakeIntVarArray(int count, long[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(values); } return array; } public IntVar[] MakeIntVarArray(int count, long[] values, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(values, var_name); } return array; } public IntVar[] MakeIntVarArray(int count, int[] values) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeIntVar(values); } return array; } public IntVar[] MakeIntVarArray(int count, int[] values, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeIntVar(values, var_name); } return array; } public IntVar[] MakeBoolVarArray(int count) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeBoolVar(); } return array; } public IntVar[] MakeBoolVarArray(int count, string name) { IntVar[] array = new IntVar[count]; for (int i = 0; i < count; ++i) { string var_name = name + i; array[i] = MakeBoolVar(var_name); } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i, j] = MakeIntVar(min, max); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long min, long max, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; array[i, j] = MakeIntVar(min, max, var_name); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i, j] = MakeIntVar(values); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, long[] values, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; array[i, j] = MakeIntVar(values, var_name); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i, j] = MakeIntVar(values); } } return array; } public IntVar[,] MakeIntVarMatrix(int rows, int cols, int[] values, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; array[i, j] = MakeIntVar(values, var_name); } } return array; } public IntVar[,] MakeBoolVarMatrix(int rows, int cols) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { array[i, j] = MakeBoolVar(); } } return array; } public IntVar[,] MakeBoolVarMatrix(int rows, int cols, string name) { IntVar[,] array = new IntVar[rows, cols]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { string var_name = name + "[" + i + ", " + j + "]"; array[i, j] = MakeBoolVar(var_name); } } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, long start_max, long duration, bool optional) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, ""); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long start_min, long start_max, long duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min, start_max, duration, optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, long[] start_min, long[] start_max, long[] duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(int count, int[] start_min, int[] start_max, int[] duration, bool optional, string name) { IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(start_min[i], start_max[i], duration[i], optional, name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, int[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } public IntervalVar[] MakeFixedDurationIntervalVarArray(IntVar[] starts, long[] durations, string name) { int count = starts.Length; IntervalVar[] array = new IntervalVar[count]; for (int i = 0; i < count; ++i) { array[i] = MakeFixedDurationIntervalVar(starts[i], durations[i], name + i); } return array; } public void NewSearch(DecisionBuilder db) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); NewSearchAux(db); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); NewSearchAux(db, sm1); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); NewSearchAux(db, sm1, sm2); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, SearchMonitor sm3) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); pinned_search_monitors_.Add(sm3); NewSearchAux(db, sm1, sm2, sm3); } public void NewSearch(DecisionBuilder db, SearchMonitor sm1, SearchMonitor sm2, SearchMonitor sm3, SearchMonitor sm4) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.Add(sm1); pinned_search_monitors_.Add(sm2); pinned_search_monitors_.Add(sm3); pinned_search_monitors_.Add(sm4); NewSearchAux(db, sm1, sm2, sm3, sm4); } public void NewSearch(DecisionBuilder db, SearchMonitor[] monitors) { pinned_decision_builder_ = db; pinned_search_monitors_.Clear(); pinned_search_monitors_.AddRange(monitors); NewSearchAux(db, monitors); } public void EndSearch() { pinned_decision_builder_ = null; pinned_search_monitors_.Clear(); EndSearchAux(); } private System.Collections.Generic.List<SearchMonitor> pinned_search_monitors_ = new System.Collections.Generic.List<SearchMonitor>(); private DecisionBuilder pinned_decision_builder_; } public partial class IntExpr : PropagationBaseObject { public static IntExpr operator +(IntExpr a, IntExpr b) { return a.solver().MakeSum(a, b); } public static IntExpr operator +(IntExpr a, long v) { return a.solver().MakeSum(a, v); } public static IntExpr operator +(long v, IntExpr a) { return a.solver().MakeSum(a, v); } public static IntExpr operator -(IntExpr a, IntExpr b) { return a.solver().MakeDifference(a, b); } public static IntExpr operator -(IntExpr a, long v) { return a.solver().MakeSum(a, -v); } public static IntExpr operator -(long v, IntExpr a) { return a.solver().MakeDifference(v, a); } public static IntExpr operator *(IntExpr a, IntExpr b) { return a.solver().MakeProd(a, b); } public static IntExpr operator *(IntExpr a, long v) { return a.solver().MakeProd(a, v); } public static IntExpr operator *(long v, IntExpr a) { return a.solver().MakeProd(a, v); } public static IntExpr operator /(IntExpr a, long v) { return a.solver().MakeDiv(a, v); } public static IntExpr operator %(IntExpr a, long v) { return a.solver().MakeModulo(a, v); } public static IntExpr operator -(IntExpr a) { return a.solver().MakeOpposite(a); } public IntExpr Abs() { return this.solver().MakeAbs(this); } public IntExpr Square() { return this.solver().MakeSquare(this); } public static IntExprEquality operator ==(IntExpr a, IntExpr b) { return new IntExprEquality(a, b, true); } public static IntExprEquality operator !=(IntExpr a, IntExpr b) { return new IntExprEquality(a, b, false); } public static WrappedConstraint operator ==(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a, v)); } public static WrappedConstraint operator !=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator >=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a, v)); } public static WrappedConstraint operator>(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeGreater(a, v)); } public static WrappedConstraint operator <=(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a, v)); } public static WrappedConstraint operator<(IntExpr a, long v) { return new WrappedConstraint(a.solver().MakeLess(a, v)); } public static WrappedConstraint operator >=(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(IntExpr a, IntExpr b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } } public partial class Constraint : PropagationBaseObject, IConstraintWithStatus { public static implicit operator IntVar(Constraint eq) { return eq.Var(); } public static implicit operator IntExpr(Constraint eq) { return eq.Var(); } public static IntExpr operator +(Constraint a, Constraint b) { return a.solver().MakeSum(a.Var(), b.Var()); } public static IntExpr operator +(Constraint a, long v) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator +(long v, Constraint a) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator -(Constraint a, Constraint b) { return a.solver().MakeDifference(a.Var(), b.Var()); } public static IntExpr operator -(Constraint a, long v) { return a.solver().MakeSum(a.Var(), -v); } public static IntExpr operator -(long v, Constraint a) { return a.solver().MakeDifference(v, a.Var()); } public static IntExpr operator *(Constraint a, Constraint b) { return a.solver().MakeProd(a.Var(), b.Var()); } public static IntExpr operator *(Constraint a, long v) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator *(long v, Constraint a) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator /(Constraint a, long v) { return a.solver().MakeDiv(a.Var(), v); } public static IntExpr operator -(Constraint a) { return a.solver().MakeOpposite(a.Var()); } public IntExpr Abs() { return this.solver().MakeAbs(this.Var()); } public IntExpr Square() { return this.solver().MakeSquare(this.Var()); } public static WrappedConstraint operator ==(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator ==(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator !=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator !=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator >=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator >=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator>(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator>(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator <=(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator <=(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator<(Constraint a, long v) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator<(long v, Constraint a) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator >=(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(Constraint a, Constraint b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } public static ConstraintEquality operator ==(Constraint a, Constraint b) { return new ConstraintEquality(a, b, true); } public static ConstraintEquality operator !=(Constraint a, Constraint b) { return new ConstraintEquality(a, b, false); } } } // namespace Google.OrTools.ConstraintSolver
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [TextOverlay.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////////// using System; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using OpenTK.Graphics.OpenGL; using PixelFormat = OpenTK.Graphics.OpenGL.PixelFormat; namespace open3mod { /// <summary> /// /// Utility class to maintain a full-size overlay for the GLControl hosting the /// scene. The overlay can be used to efficiently draw text messages on top /// of everything. /// /// The concept is easy, anyone who wants to draw a text can obtain a .net /// drawing context and draw whatever they like. Text drawers need to take /// care not to interfere with each other's regions since they will easily /// overwrite other text. /// /// Based on http://www.opentk.com/doc/graphics/how-to-render-text-using-opengl /// </summary> public class TextOverlay : IDisposable { private readonly Renderer _renderer; private Bitmap _textBmp; private int _textTexture; private Graphics _tempContext; private bool _disposed; public bool WantRedraw { get { return _tempContext != null; } } public bool WantRedrawNextFrame { get; set; } public TextOverlay(Renderer renderer) { _renderer = renderer; // Create Bitmap and OpenGL texture var cs = renderer.RenderResolution; _textBmp = new Bitmap(cs.Width, cs.Height); // match window size _textTexture = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, _textTexture); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); // just allocate memory, so we can update efficiently using TexSubImage2D GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, _textBmp.Width, _textBmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); } /// <summary> /// Invoked by the Renderer class when the size of the Gl control changes. /// This will automatically clear all text. /// </summary> public void Resize() { var cs = _renderer.RenderResolution; if (cs.Width == 0 || cs.Height == 0) { return; } _textBmp.Dispose(); _textBmp = new Bitmap(cs.Width, cs.Height); GL.BindTexture(TextureTarget.Texture2D, _textTexture); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, _textBmp.Width, _textBmp.Height, 0, PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero); GetDrawableGraphicsContext(); } /// <summary> /// Obtain a drawable context so the caller can draw text and mark the text /// content as dirty to enforce automatic updating of the underlying Gl /// resources. /// </summary> /// <returns>Context to draw to or a null if resources have been /// disposed already.</returns> public Graphics GetDrawableGraphicsContext() { if(_disposed) { return null; } if(_tempContext == null) { try { _tempContext = Graphics.FromImage(_textBmp); } catch(Exception) { // this happens when _textBmp is not a valid bitmap. It seems, this // can happen if the application is inactive and then switched to. // todo: find out how to avoid this. _tempContext = null; return null; } _tempContext.Clear(Color.Transparent); _tempContext.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; } return _tempContext; } /// <summary> /// Clears the entire overlay /// </summary> public void Clear() { if (_tempContext == null) { _tempContext = Graphics.FromImage(_textBmp); } _tempContext.Clear(Color.Transparent); } #if DEBUG ~TextOverlay() { // bad, OpenTK is not safe to use from within finalizers. // Dispose() should be called manually. Debug.Assert(false); } #endif public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (disposing) { if (_textBmp != null) { _textBmp.Dispose(); _textBmp = null; } if (_tempContext != null) { _tempContext.Dispose(); _tempContext = null; } } if (_textTexture > 0) { GL.DeleteTexture(_textTexture); _textTexture = 0; } } public void Draw() { // Updates the GL texture if there were any changes to the .net offscreen buffer. if(_tempContext != null) { Commit(); _tempContext.Dispose(); _tempContext = null; } GL.MatrixMode(MatrixMode.Modelview); GL.PushMatrix(); GL.LoadIdentity(); // Draw a full screen quad with the text texture on top GL.MatrixMode(MatrixMode.Projection); GL.PushMatrix(); GL.LoadIdentity(); var cs = _renderer.RenderResolution; GL.Ortho(0, cs.Width, cs.Height, 0, -1, 1); GL.Enable(EnableCap.Texture2D); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.SrcAlpha, BlendingFactorDest.OneMinusSrcAlpha); GL.BindTexture(TextureTarget.Texture2D, _textTexture); const float offset = 0; // clear color GL.Color3(1.0f,1.0f,1.0f); GL.Begin(BeginMode.Quads); GL.TexCoord2(0f, 0f); GL.Vertex2(0f - offset, 0f - offset); GL.TexCoord2(1f, 0f); GL.Vertex2(cs.Width - offset, 0f - offset); GL.TexCoord2(1f, 1f); GL.Vertex2(cs.Width - offset, cs.Height - offset); GL.TexCoord2(0f, 1f); GL.Vertex2(0f - offset, cs.Height - offset); GL.End(); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.Texture2D); GL.PopMatrix(); GL.MatrixMode(MatrixMode.Modelview); GL.PopMatrix(); if (WantRedrawNextFrame) { GetDrawableGraphicsContext(); WantRedrawNextFrame = false; } } /// <summary> /// Commit all changes to OpenGl /// </summary> private void Commit() { try { var data = _textBmp.LockBits(new Rectangle(0, 0, _textBmp.Width, _textBmp.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.BindTexture(TextureTarget.Texture2D, _textTexture); GL.TexSubImage2D(TextureTarget.Texture2D, 0, 0, 0, _textBmp.Width, _textBmp.Height, PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); _textBmp.UnlockBits(data); } catch(ArgumentException) { // this sometimes happens during Shutdown (presumably because Commit gets called // after other resources have already been cleaned up). Ignore it because it // doesn't matter at this time. } } } } /* vi: set shiftwidth=4 tabstop=4: */
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.SymbolSearch; using Microsoft.VisualStudio.LanguageServices.Utilities; using Microsoft.VisualStudio.Shell.Interop; using NuGet.VisualStudio; using Roslyn.Utilities; using SVsServiceProvider = Microsoft.VisualStudio.Shell.SVsServiceProvider; namespace Microsoft.VisualStudio.LanguageServices.Packaging { /// <summary> /// Free threaded wrapper around the NuGet.VisualStudio STA package installer interfaces. /// We want to be able to make queries about packages from any thread. For example, the /// add-NuGet-reference feature wants to know what packages a project already has /// references to. NuGet.VisualStudio provides this information, but only in a COM STA /// manner. As we don't want our background work to bounce and block on the UI thread /// we have this helper class which queries the information on the UI thread and caches /// the data so it can be read from the background. /// </summary> [ExportWorkspaceService(typeof(IPackageInstallerService)), Shared] internal partial class PackageInstallerService : AbstractDelayStartedService, IPackageInstallerService, IVsSearchProviderCallback { private readonly object _gate = new object(); private readonly VisualStudioWorkspaceImpl _workspace; private readonly SVsServiceProvider _serviceProvider; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; // We refer to the package services through proxy types so that we can // delay loading their DLLs until we actually need them. private IPackageServicesProxy _packageServices; private CancellationTokenSource _tokenSource = new CancellationTokenSource(); // We keep track of what types of changes we've seen so we can then determine what to // refresh on the UI thread. If we hear about project changes, we only refresh that // project. If we hear about a solution level change, we'll refresh all projects. private bool _solutionChanged; private HashSet<ProjectId> _changedProjects = new HashSet<ProjectId>(); private readonly ConcurrentDictionary<ProjectId, ProjectState> _projectToInstalledPackageAndVersion = new ConcurrentDictionary<ProjectId, ProjectState>(); [ImportingConstructor] public PackageInstallerService( VisualStudioWorkspaceImpl workspace, SVsServiceProvider serviceProvider, IVsEditorAdaptersFactoryService editorAdaptersFactoryService) : base(workspace, SymbolSearchOptions.Enabled, SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, SymbolSearchOptions.SuggestForTypesInNuGetPackages) { _workspace = workspace; _serviceProvider = serviceProvider; _editorAdaptersFactoryService = editorAdaptersFactoryService; } public ImmutableArray<PackageSource> PackageSources { get; private set; } = ImmutableArray<PackageSource>.Empty; public event EventHandler PackageSourcesChanged; private bool IsEnabled => _packageServices != null; bool IPackageInstallerService.IsEnabled(ProjectId projectId) { if (_packageServices == null) { return false; } if (_projectToInstalledPackageAndVersion.TryGetValue(projectId, out var state)) { return state.IsEnabled; } // If we haven't scanned the project yet, assume that we're available for it. return true; } protected override void EnableService() { // Our service has been enabled. Now load the VS package dlls. var componentModel = (IComponentModel)_serviceProvider.GetService(typeof(SComponentModel)); var packageInstallerServices = componentModel.GetExtensions<IVsPackageInstallerServices>().FirstOrDefault(); var packageInstaller = componentModel.GetExtensions<IVsPackageInstaller2>().FirstOrDefault(); var packageUninstaller = componentModel.GetExtensions<IVsPackageUninstaller>().FirstOrDefault(); var packageSourceProvider = componentModel.GetExtensions<IVsPackageSourceProvider>().FirstOrDefault(); if (packageInstallerServices == null || packageInstaller == null || packageUninstaller == null || packageSourceProvider == null) { return; } _packageServices = new PackageServicesProxy( packageInstallerServices, packageInstaller, packageUninstaller, packageSourceProvider); // Start listening to additional events workspace changes. _workspace.WorkspaceChanged += OnWorkspaceChanged; _packageServices.SourcesChanged += OnSourceProviderSourcesChanged; } protected override void StartWorking() { this.AssertIsForeground(); if (!this.IsEnabled) { return; } OnSourceProviderSourcesChanged(this, EventArgs.Empty); OnWorkspaceChanged(null, new WorkspaceChangeEventArgs( WorkspaceChangeKind.SolutionAdded, null, null)); } private void OnSourceProviderSourcesChanged(object sender, EventArgs e) { if (!this.IsForeground()) { this.InvokeBelowInputPriority(() => OnSourceProviderSourcesChanged(sender, e)); return; } this.AssertIsForeground(); PackageSources = _packageServices.GetSources(includeUnOfficial: true, includeDisabled: false) .Select(r => new PackageSource(r.Key, r.Value)) .ToImmutableArrayOrEmpty(); PackageSourcesChanged?.Invoke(this, EventArgs.Empty); } public bool TryInstallPackage( Workspace workspace, DocumentId documentId, string source, string packageName, string versionOpt, bool includePrerelease, CancellationToken cancellationToken) { this.AssertIsForeground(); // The 'workspace == _workspace' line is probably not necessary. However, we include // it just to make sure that someone isn't trying to install a package into a workspace // other than the VisualStudioWorkspace. if (workspace == _workspace && _workspace != null && _packageServices != null) { var projectId = documentId.ProjectId; var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(SDTE)); var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject != null) { var description = string.Format(ServicesVSResources.Install_0, packageName); var undoManager = _editorAdaptersFactoryService.TryGetUndoManager( workspace, documentId, cancellationToken); return TryInstallAndAddUndoAction( source, packageName, versionOpt, includePrerelease, dte, dteProject, undoManager); } } return false; } private bool TryInstallPackage( string source, string packageName, string versionOpt, bool includePrerelease, EnvDTE.DTE dte, EnvDTE.Project dteProject) { try { if (!_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0, packageName); if (versionOpt == null) { _packageServices.InstallLatestPackage( source, dteProject, packageName, includePrerelease, ignoreDependencies: false); } else { _packageServices.InstallPackage( source, dteProject, packageName, versionOpt, ignoreDependencies: false); } var installedVersion = GetInstalledVersion(packageName, dteProject); dte.StatusBar.Text = string.Format(ServicesVSResources.Installing_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_install_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Installing_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private static string GetStatusBarText(string packageName, string installedVersion) { return installedVersion == null ? packageName : $"{packageName} - {installedVersion}"; } private bool TryUninstallPackage( string packageName, EnvDTE.DTE dte, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { if (_packageServices.IsPackageInstalled(dteProject, packageName)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0, packageName); var installedVersion = GetInstalledVersion(packageName, dteProject); _packageServices.UninstallPackage(dteProject, packageName, removeDependencies: true); dte.StatusBar.Text = string.Format(ServicesVSResources.Uninstalling_0_completed, GetStatusBarText(packageName, installedVersion)); return true; } // fall through. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { dte.StatusBar.Text = string.Format(ServicesVSResources.Package_uninstall_failed_colon_0, e.Message); var notificationService = _workspace.Services.GetService<INotificationService>(); notificationService?.SendNotification( string.Format(ServicesVSResources.Uninstalling_0_failed_Additional_information_colon_1, packageName, e.Message), severity: NotificationSeverity.Error); // fall through. } return false; } private string GetInstalledVersion(string packageName, EnvDTE.Project dteProject) { this.AssertIsForeground(); try { var installedPackages = _packageServices.GetInstalledPackages(dteProject); var metadata = installedPackages.FirstOrDefault(m => m.Id == packageName); return metadata?.VersionString; } catch (ArgumentException e) when (IsKnownNugetIssue(e)) { // Nuget may throw an ArgumentException when there is something about the project // they do not like/support. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } return null; } private bool IsKnownNugetIssue(ArgumentException exception) { // See https://github.com/NuGet/Home/issues/4706 // Nuget throws on legal projects. We do not want to report this exception // as it is known (and NFWs are expensive), but we do want to report if we // run into anything else. return exception.Message.Contains("is not a valid version string"); } private void OnWorkspaceChanged(object sender, WorkspaceChangeEventArgs e) { ThisCanBeCalledOnAnyThread(); bool localSolutionChanged = false; ProjectId localChangedProject = null; switch (e.Kind) { default: // Nothing to do for any other events. return; case WorkspaceChangeKind.ProjectAdded: case WorkspaceChangeKind.ProjectChanged: case WorkspaceChangeKind.ProjectReloaded: case WorkspaceChangeKind.ProjectRemoved: localChangedProject = e.ProjectId; break; case WorkspaceChangeKind.SolutionAdded: case WorkspaceChangeKind.SolutionChanged: case WorkspaceChangeKind.SolutionCleared: case WorkspaceChangeKind.SolutionReloaded: case WorkspaceChangeKind.SolutionRemoved: localSolutionChanged = true; break; } lock (_gate) { // Augment the data that the foreground thread will process. _solutionChanged |= localSolutionChanged; if (localChangedProject != null) { _changedProjects.Add(localChangedProject); } // Now cancel any inflight work that is processing the data. _tokenSource.Cancel(); _tokenSource = new CancellationTokenSource(); // And enqueue a new job to process things. Wait one second before starting. // That way if we get a flurry of events we'll end up processing them after // they've all come in. var cancellationToken = _tokenSource.Token; Task.Delay(TimeSpan.FromSeconds(1), cancellationToken) .ContinueWith(_ => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler); } } private void ProcessBatchedChangesOnForeground(CancellationToken cancellationToken) { this.AssertIsForeground(); // If we've been asked to stop, then there's no point proceeding. if (cancellationToken.IsCancellationRequested) { return; } // If we've been disconnected, then there's no point proceeding. if (_workspace == null || _packageServices == null) { return; } // Get a project to process. var solution = _workspace.CurrentSolution; var projectId = DequeueNextProject(solution); if (projectId == null) { // No project to process, nothing to do. return; } // Process this single project. ProcessProjectChange(solution, projectId); // After processing this single project, yield so the foreground thread // can do more work. Then go and loop again so we can process the // rest of the projects. Task.Factory.SafeStartNew( () => ProcessBatchedChangesOnForeground(cancellationToken), cancellationToken, ForegroundTaskScheduler); } private ProjectId DequeueNextProject(Solution solution) { this.AssertIsForeground(); lock (_gate) { // If we detected a solution change, then we need to process all projects. // This includes all the projects that we already know about, as well as // all the projects in the current workspace solution. if (_solutionChanged) { _changedProjects.AddRange(solution.ProjectIds); _changedProjects.AddRange(_projectToInstalledPackageAndVersion.Keys); } _solutionChanged = false; // Remove and return the first project in the list. var projectId = _changedProjects.FirstOrDefault(); _changedProjects.Remove(projectId); return projectId; } } private void ProcessProjectChange(Solution solution, ProjectId projectId) { this.AssertIsForeground(); // Remove anything we have associated with this project. _projectToInstalledPackageAndVersion.TryRemove(projectId, out var projectState); var project = solution.GetProject(projectId); if (project == null) { // Project was removed. Nothing needs to be done. return; } // We really only need to know the NuGet status for managed language projects. // Also, the NuGet APIs may throw on some projects that don't implement the // full set of DTE APIs they expect. So we filter down to just C# and VB here // as we know these languages are safe to build up this index for. if (project.Language != LanguageNames.CSharp && project.Language != LanguageNames.VisualBasic) { return; } // Project was changed in some way. Let's go find the set of installed packages for it. var dteProject = _workspace.TryGetDTEProject(projectId); if (dteProject == null) { // Don't have a DTE project for this project ID. not something we can query NuGet for. return; } var installedPackages = new MultiDictionary<string, string>(); var isEnabled = false; // Calling into NuGet. Assume they may fail for any reason. try { var installedPackageMetadata = _packageServices.GetInstalledPackages(dteProject); foreach (var metadata in installedPackageMetadata) { if (metadata.VersionString != null) { installedPackages.Add(metadata.Id, metadata.VersionString); } } isEnabled = true; } catch (ArgumentException e) when (IsKnownNugetIssue(e)) { // Nuget may throw an ArgumentException when there is something about the project // they do not like/support. } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { } var state = new ProjectState(isEnabled, installedPackages); _projectToInstalledPackageAndVersion.AddOrUpdate( projectId, state, (_1, _2) => state); } public bool IsInstalled(Workspace workspace, ProjectId projectId, string packageName) { ThisCanBeCalledOnAnyThread(); return _projectToInstalledPackageAndVersion.TryGetValue(projectId, out var installedPackages) && installedPackages.InstalledPackageToVersion.ContainsKey(packageName); } public ImmutableArray<string> GetInstalledVersions(string packageName) { ThisCanBeCalledOnAnyThread(); var installedVersions = new HashSet<string>(); foreach (var state in _projectToInstalledPackageAndVersion.Values) { installedVersions.AddRange(state.InstalledPackageToVersion[packageName]); } // Order the versions with a weak heuristic so that 'newer' versions come first. // Essentially, we try to break the version on dots, and then we use a LogicalComparer // to try to more naturally order the things we see between the dots. var versionsAndSplits = installedVersions.Select(v => new { Version = v, Split = v.Split('.') }).ToList(); versionsAndSplits.Sort((v1, v2) => { var diff = CompareSplit(v1.Split, v2.Split); return diff != 0 ? diff : -v1.Version.CompareTo(v2.Version); }); return versionsAndSplits.Select(v => v.Version).ToImmutableArray(); } private int CompareSplit(string[] split1, string[] split2) { ThisCanBeCalledOnAnyThread(); for (int i = 0, n = Math.Min(split1.Length, split2.Length); i < n; i++) { // Prefer things that look larger. i.e. 7 should come before 6. // Use a logical string comparer so that 10 is understood to be // greater than 3. var diff = -LogicalStringComparer.Instance.Compare(split1[i], split2[i]); if (diff != 0) { return diff; } } // Choose the one with more parts. return split2.Length - split1.Length; } public IEnumerable<Project> GetProjectsWithInstalledPackage(Solution solution, string packageName, string version) { ThisCanBeCalledOnAnyThread(); var result = new List<Project>(); foreach (var kvp in this._projectToInstalledPackageAndVersion) { var state = kvp.Value; var versionSet = state.InstalledPackageToVersion[packageName]; if (versionSet.Contains(version)) { var project = solution.GetProject(kvp.Key); if (project != null) { result.Add(project); } } } return result; } public void ShowManagePackagesDialog(string packageName) { this.AssertIsForeground(); var shell = (IVsShell)_serviceProvider.GetService(typeof(SVsShell)); if (shell == null) { return; } var nugetGuid = new Guid("5fcc8577-4feb-4d04-ad72-d6c629b083cc"); shell.LoadPackage(ref nugetGuid, out var nugetPackage); if (nugetPackage == null) { return; } // We're able to launch the package manager (with an item in its search box) by // using the IVsSearchProvider API that the NuGet package exposes. // // We get that interface for it and then pass it a SearchQuery that effectively // wraps the package name we're looking for. The NuGet package will then read // out that string and populate their search box with it. var extensionProvider = (IVsPackageExtensionProvider)nugetPackage; var extensionGuid = new Guid("042C2B4B-C7F7-49DB-B7A2-402EB8DC7892"); var emptyGuid = Guid.Empty; var searchProvider = (IVsSearchProvider)extensionProvider.CreateExtensionInstance(ref emptyGuid, ref extensionGuid); var task = searchProvider.CreateSearch(dwCookie: 1, pSearchQuery: new SearchQuery(packageName), pSearchCallback: this); task.Start(); } public void ReportProgress(IVsSearchTask pTask, uint dwProgress, uint dwMaxProgress) { } public void ReportComplete(IVsSearchTask pTask, uint dwResultsFound) { } public void ReportResult(IVsSearchTask pTask, IVsSearchItemResult pSearchItemResult) { pSearchItemResult.InvokeAction(); } public void ReportResults(IVsSearchTask pTask, uint dwResults, IVsSearchItemResult[] pSearchItemResults) { } private class SearchQuery : IVsSearchQuery { public SearchQuery(string packageName) { this.SearchString = packageName; } public string SearchString { get; } public uint ParseError => 0; public uint GetTokens(uint dwMaxTokens, IVsSearchToken[] rgpSearchTokens) { return 0; } } private class PackageServicesProxy : IPackageServicesProxy { private readonly IVsPackageInstaller2 _packageInstaller; private readonly IVsPackageInstallerServices _packageInstallerServices; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly IVsPackageUninstaller _packageUninstaller; public PackageServicesProxy( IVsPackageInstallerServices packageInstallerServices, IVsPackageInstaller2 packageInstaller, IVsPackageUninstaller packageUninstaller, IVsPackageSourceProvider packageSourceProvider) { _packageInstallerServices = packageInstallerServices; _packageInstaller = packageInstaller; _packageUninstaller = packageUninstaller; _packageSourceProvider = packageSourceProvider; } public event EventHandler SourcesChanged { add { _packageSourceProvider.SourcesChanged += value; } remove { _packageSourceProvider.SourcesChanged -= value; } } public IEnumerable<PackageMetadata> GetInstalledPackages(EnvDTE.Project project) { return _packageInstallerServices.GetInstalledPackages(project) .Select(m => new PackageMetadata(m.Id, m.VersionString)) .ToList(); } public bool IsPackageInstalled(EnvDTE.Project project, string id) => _packageInstallerServices.IsPackageInstalled(project, id); public void InstallPackage(string source, EnvDTE.Project project, string packageId, string version, bool ignoreDependencies) => _packageInstaller.InstallPackage(source, project, packageId, version, ignoreDependencies); public void InstallLatestPackage(string source, EnvDTE.Project project, string packageId, bool includePrerelease, bool ignoreDependencies) => _packageInstaller.InstallLatestPackage(source, project, packageId, includePrerelease, ignoreDependencies); public IEnumerable<KeyValuePair<string, string>> GetSources(bool includeUnOfficial, bool includeDisabled) => _packageSourceProvider.GetSources(includeUnOfficial, includeDisabled); public void UninstallPackage(EnvDTE.Project project, string packageId, bool removeDependencies) => _packageUninstaller.UninstallPackage(project, packageId, removeDependencies); } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects.GuiControls { public unsafe class GuiCurveCtrl : GuiControl { public GuiCurveCtrl() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.GuiCurveCtrlCreateInstance()); } public GuiCurveCtrl(uint pId) : base(pId) { } public GuiCurveCtrl(string pName) : base(pName) { } public GuiCurveCtrl(IntPtr pObjPtr) : base(pObjPtr) { } public GuiCurveCtrl(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public GuiCurveCtrl(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlGetStart(IntPtr ctrl, out Point2I outPos); private static _GuiCurveCtrlGetStart _GuiCurveCtrlGetStartFunc; internal static void GuiCurveCtrlGetStart(IntPtr ctrl, out Point2I outPos) { if (_GuiCurveCtrlGetStartFunc == null) { _GuiCurveCtrlGetStartFunc = (_GuiCurveCtrlGetStart)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetStart"), typeof(_GuiCurveCtrlGetStart)); } _GuiCurveCtrlGetStartFunc(ctrl, out outPos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetStart(IntPtr ctrl, Point2I pos); private static _GuiCurveCtrlSetStart _GuiCurveCtrlSetStartFunc; internal static void GuiCurveCtrlSetStart(IntPtr ctrl, Point2I pos) { if (_GuiCurveCtrlSetStartFunc == null) { _GuiCurveCtrlSetStartFunc = (_GuiCurveCtrlSetStart)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetStart"), typeof(_GuiCurveCtrlSetStart)); } _GuiCurveCtrlSetStartFunc(ctrl, pos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlGetEnd(IntPtr ctrl, out Point2I outPos); private static _GuiCurveCtrlGetEnd _GuiCurveCtrlGetEndFunc; internal static void GuiCurveCtrlGetEnd(IntPtr ctrl, out Point2I outPos) { if (_GuiCurveCtrlGetEndFunc == null) { _GuiCurveCtrlGetEndFunc = (_GuiCurveCtrlGetEnd)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetEnd"), typeof(_GuiCurveCtrlGetEnd)); } _GuiCurveCtrlGetEndFunc(ctrl, out outPos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetEnd(IntPtr ctrl, Point2I pos); private static _GuiCurveCtrlSetEnd _GuiCurveCtrlSetEndFunc; internal static void GuiCurveCtrlSetEnd(IntPtr ctrl, Point2I pos) { if (_GuiCurveCtrlSetEndFunc == null) { _GuiCurveCtrlSetEndFunc = (_GuiCurveCtrlSetEnd)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetEnd"), typeof(_GuiCurveCtrlSetEnd)); } _GuiCurveCtrlSetEndFunc(ctrl, pos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlGetControlA(IntPtr ctrl, out Point2I outPos); private static _GuiCurveCtrlGetControlA _GuiCurveCtrlGetControlAFunc; internal static void GuiCurveCtrlGetControlA(IntPtr ctrl, out Point2I outPos) { if (_GuiCurveCtrlGetControlAFunc == null) { _GuiCurveCtrlGetControlAFunc = (_GuiCurveCtrlGetControlA)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetControlA"), typeof(_GuiCurveCtrlGetControlA)); } _GuiCurveCtrlGetControlAFunc(ctrl, out outPos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetControlA(IntPtr ctrl, Point2I pos); private static _GuiCurveCtrlSetControlA _GuiCurveCtrlSetControlAFunc; internal static void GuiCurveCtrlSetControlA(IntPtr ctrl, Point2I pos) { if (_GuiCurveCtrlSetControlAFunc == null) { _GuiCurveCtrlSetControlAFunc = (_GuiCurveCtrlSetControlA)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetControlA"), typeof(_GuiCurveCtrlSetControlA)); } _GuiCurveCtrlSetControlAFunc(ctrl, pos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlGetControlB(IntPtr ctrl, out Point2I outPos); private static _GuiCurveCtrlGetControlB _GuiCurveCtrlGetControlBFunc; internal static void GuiCurveCtrlGetControlB(IntPtr ctrl, out Point2I outPos) { if (_GuiCurveCtrlGetControlBFunc == null) { _GuiCurveCtrlGetControlBFunc = (_GuiCurveCtrlGetControlB)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetControlB"), typeof(_GuiCurveCtrlGetControlB)); } _GuiCurveCtrlGetControlBFunc(ctrl, out outPos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetControlB(IntPtr ctrl, Point2I pos); private static _GuiCurveCtrlSetControlB _GuiCurveCtrlSetControlBFunc; internal static void GuiCurveCtrlSetControlB(IntPtr ctrl, Point2I pos) { if (_GuiCurveCtrlSetControlBFunc == null) { _GuiCurveCtrlSetControlBFunc = (_GuiCurveCtrlSetControlB)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetControlB"), typeof(_GuiCurveCtrlSetControlB)); } _GuiCurveCtrlSetControlBFunc(ctrl, pos); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlGetColor(IntPtr ctrl, out Color outCol); private static _GuiCurveCtrlGetColor _GuiCurveCtrlGetColorFunc; internal static void GuiCurveCtrlGetColor(IntPtr ctrl, out Color outCol) { if (_GuiCurveCtrlGetColorFunc == null) { _GuiCurveCtrlGetColorFunc = (_GuiCurveCtrlGetColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetColor"), typeof(_GuiCurveCtrlGetColor)); } _GuiCurveCtrlGetColorFunc(ctrl, out outCol); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetColor(IntPtr ctrl, Color color); private static _GuiCurveCtrlSetColor _GuiCurveCtrlSetColorFunc; internal static void GuiCurveCtrlSetColor(IntPtr ctrl, Color color) { if (_GuiCurveCtrlSetColorFunc == null) { _GuiCurveCtrlSetColorFunc = (_GuiCurveCtrlSetColor)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetColor"), typeof(_GuiCurveCtrlSetColor)); } _GuiCurveCtrlSetColorFunc(ctrl, color); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate float _GuiCurveCtrlGetThickness(IntPtr ctrl); private static _GuiCurveCtrlGetThickness _GuiCurveCtrlGetThicknessFunc; internal static float GuiCurveCtrlGetThickness(IntPtr ctrl) { if (_GuiCurveCtrlGetThicknessFunc == null) { _GuiCurveCtrlGetThicknessFunc = (_GuiCurveCtrlGetThickness)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlGetThickness"), typeof(_GuiCurveCtrlGetThickness)); } return _GuiCurveCtrlGetThicknessFunc(ctrl); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void _GuiCurveCtrlSetThickness(IntPtr ctrl, float thickness); private static _GuiCurveCtrlSetThickness _GuiCurveCtrlSetThicknessFunc; internal static void GuiCurveCtrlSetThickness(IntPtr ctrl, float thickness) { if (_GuiCurveCtrlSetThicknessFunc == null) { _GuiCurveCtrlSetThicknessFunc = (_GuiCurveCtrlSetThickness)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlSetThickness"), typeof(_GuiCurveCtrlSetThickness)); } _GuiCurveCtrlSetThicknessFunc(ctrl, thickness); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _GuiCurveCtrlCreateInstance(); private static _GuiCurveCtrlCreateInstance _GuiCurveCtrlCreateInstanceFunc; internal static IntPtr GuiCurveCtrlCreateInstance() { if (_GuiCurveCtrlCreateInstanceFunc == null) { _GuiCurveCtrlCreateInstanceFunc = (_GuiCurveCtrlCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "GuiCurveCtrlCreateInstance"), typeof(_GuiCurveCtrlCreateInstance)); } return _GuiCurveCtrlCreateInstanceFunc(); } } #endregion #region Properties public Point2I Start { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); Point2I outVal; InternalUnsafeMethods.GuiCurveCtrlGetStart(ObjectPtr->ObjPtr, out outVal); return outVal; } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetStart(ObjectPtr->ObjPtr, value); } } public Point2I End { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); Point2I outVal; InternalUnsafeMethods.GuiCurveCtrlGetEnd(ObjectPtr->ObjPtr, out outVal); return outVal; } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetEnd(ObjectPtr->ObjPtr, value); } } public Point2I ControlA { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); Point2I outVal; InternalUnsafeMethods.GuiCurveCtrlGetControlA(ObjectPtr->ObjPtr, out outVal); return outVal; } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetControlA(ObjectPtr->ObjPtr, value); } } public Point2I ControlB { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); Point2I outVal; InternalUnsafeMethods.GuiCurveCtrlGetControlB(ObjectPtr->ObjPtr, out outVal); return outVal; } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetControlB(ObjectPtr->ObjPtr, value); } } public Color Color { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); Color outVal; InternalUnsafeMethods.GuiCurveCtrlGetColor(ObjectPtr->ObjPtr, out outVal); return outVal; } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetColor(ObjectPtr->ObjPtr, value); } } public float Thickness { get { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.GuiCurveCtrlGetThickness(ObjectPtr->ObjPtr); } set { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); InternalUnsafeMethods.GuiCurveCtrlSetThickness(ObjectPtr->ObjPtr, value); } } #endregion #region Methods #endregion } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Net; using System.Net.Sockets; struct HttpWrapper { internal static HttpApiVersion HttpApiVersion1 = new HttpApiVersion(1, 0); internal static HttpApiVersion HttpApiVersion2 = new HttpApiVersion(2, 0); } // HTTP_SERVICE_CONFIG_ID enum HttpServiceConfigId { HttpServiceConfigIPListenList = 0, HttpServiceConfigSSLCertInfo, HttpServiceConfigUrlAclInfo, HttpServiceConfigSSLCertInfoSafe, HttpServiceConfigTimeout, HttpServiceConfigMax } // HTTP_API_VERSION [StructLayout(LayoutKind.Sequential, Pack = 2)] struct HttpApiVersion { internal ushort HttpApiMajorVersion; internal ushort HttpApiMinorVersion; internal HttpApiVersion(ushort majorVersion, ushort minorVersion) { HttpApiMajorVersion = majorVersion; HttpApiMinorVersion = minorVersion; } } // HTTP_SERVICE_CONFIG_SSL_SET [StructLayout(LayoutKind.Sequential)] struct HttpServiceConfigSslSet { internal HttpServiceConfigSslKey KeyDesc; internal HttpServiceConfigSslParam ParamDesc; } // HTTP_SERVICE_CONFIG_SSL_KEY [StructLayout(LayoutKind.Sequential)] struct HttpServiceConfigSslKey { internal IntPtr pIpPort; } // HTTP_SERVICE_CONFIG_SSL_PARAM [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct HttpServiceConfigSslParam { internal int SslHashLength; internal SafeLocalAllocation pSslHash; internal Guid AppId; [MarshalAs(UnmanagedType.LPWStr)] internal string pSslCertStoreName; internal int DefaultCertCheckMode; internal int DefaultRevocationFreshnessTime; internal int DefaultRevocationUrlRetrievalTimeout; [MarshalAs(UnmanagedType.LPWStr)] internal string pDefaultSslCtlIdentifier; [MarshalAs(UnmanagedType.LPWStr)] internal string pDefaultSslCtlStoreName; internal int DefaultFlags; } // HTTP_SERVICE_CONFIG_APP_REFERENCE [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct HttpServiceConfigAppReference { internal Guid AppGuid; [MarshalAs(UnmanagedType.LPWStr)] internal string AppFriendlyName; [MarshalAs(UnmanagedType.Bool)] internal bool IsLegacyreference; } // HTTP_SERVICE_CONFIG_URLACL_SET [StructLayout(LayoutKind.Sequential)] struct HttpServiceConfigUrlAclSet { internal HttpServiceConfigUrlAclKey KeyDesc; internal HttpServiceConfigUrlAclParam ParamDesc; } // HTTP_SERVICE_CONFIG_URLACL_KEY [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct HttpServiceConfigUrlAclKey { [MarshalAs(UnmanagedType.LPWStr)] internal string pUrlPrefix; internal HttpServiceConfigUrlAclKey(string urlPrefix) { pUrlPrefix = urlPrefix; } } // HTTP_SERVICE_CONFIG_URLACL_PARAM [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] struct HttpServiceConfigUrlAclParam { [MarshalAs(UnmanagedType.LPWStr)] internal string pStringSecurityDescriptor; internal HttpServiceConfigUrlAclParam(string securityDescriptor) { pStringSecurityDescriptor = securityDescriptor; } } // SOCKADDR class WinsockSockAddr : IDisposable { const Int16 AF_INET = 2; const Int16 AF_INET6 = 23; object address; GCHandle pinnedAddress; IntPtr pAddress; [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct SOCKADDR_IN { internal Int16 family; internal Int16 port; internal Byte addr00; internal Byte addr01; internal Byte addr02; internal Byte addr03; internal Int32 nothing; } [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct SOCKADDR_IN6 { internal Int16 family; internal Int16 port; internal Int32 flowInfo; internal Byte addr00; internal Byte addr01; internal Byte addr02; internal Byte addr03; internal Byte addr04; internal Byte addr05; internal Byte addr06; internal Byte addr07; internal Byte addr08; internal Byte addr09; internal Byte addr10; internal Byte addr11; internal Byte addr12; internal Byte addr13; internal Byte addr14; internal Byte addr15; public Int32 scopeID; } internal WinsockSockAddr(IPAddress source, short port) { pAddress = IntPtr.Zero; if (source.AddressFamily == AddressFamily.InterNetwork) { SOCKADDR_IN a; Byte[] addr = source.GetAddressBytes(); a.family = AF_INET; a.port = IPAddress.HostToNetworkOrder(port); a.addr00 = addr[0]; a.addr01 = addr[1]; a.addr02 = addr[2]; a.addr03 = addr[3]; a.nothing = 0; address = a; } else if (source.AddressFamily == AddressFamily.InterNetworkV6) { SOCKADDR_IN6 a; Byte[] addr = source.GetAddressBytes(); a.family = AF_INET6; a.port = IPAddress.HostToNetworkOrder(port); a.flowInfo = 0; a.addr00 = addr[0]; a.addr01 = addr[1]; a.addr02 = addr[2]; a.addr03 = addr[3]; a.addr04 = addr[4]; a.addr05 = addr[5]; a.addr06 = addr[6]; a.addr07 = addr[7]; a.addr08 = addr[8]; a.addr09 = addr[9]; a.addr10 = addr[10]; a.addr11 = addr[11]; a.addr12 = addr[12]; a.addr13 = addr[13]; a.addr14 = addr[14]; a.addr15 = addr[15]; a.scopeID = (Int32)source.ScopeId; address = a; } pinnedAddress = GCHandle.Alloc(address, GCHandleType.Pinned); pAddress = pinnedAddress.AddrOfPinnedObject(); } public void Dispose() { Close(); GC.SuppressFinalize(this); } void Close() { if (pinnedAddress.IsAllocated) { pinnedAddress.Free(); } address = null; pAddress = IntPtr.Zero; } ~WinsockSockAddr() { Close(); } internal IntPtr PinnedSockAddr { get { return pAddress; } } } }
// Copyright (c) 2002-2019 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Diagnostics.CodeAnalysis; using System.Linq; using FluentAssertions; //The only imported needed for using this driver using Neo4j.Driver; using Neo4j.Driver.IntegrationTests; using Neo4j.Driver.IntegrationTests.Internals; using Xunit; using Xunit.Abstractions; namespace Neo4j.Driver.Examples { /// <summary> /// The driver examples since 1.2 driver /// </summary> public class Examples { [SuppressMessage("ReSharper", "xUnit1013")] public class AutocommitTransactionExample : BaseExample { public AutocommitTransactionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::autocommit-transaction[] public void AddPerson(string name) { using (var session = Driver.Session()) { session.Run("CREATE (a:Person {name: $name})", new {name}); } } // end::autocommit-transaction[] [RequireServerFact] public void TestAutocommitTransactionExample() { // Given & When AddPerson("Alice"); // Then CountPerson("Alice").Should().Be(1); } } public class BasicAuthExample : BaseExample { public BasicAuthExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::basic-auth[] public IDriver CreateDriverWithBasicAuth(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password)); } // end::basic-auth[] [RequireServerFact] public void TestBasicAuthExample() { // Given using (var driver = CreateDriverWithBasicAuth(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class ConfigConnectionPoolExample : BaseExample { public ConfigConnectionPoolExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::config-connection-pool[] public IDriver CreateDriverWithCustomizedConnectionPool(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password), new Config { MaxConnectionLifetime = TimeSpan.FromMinutes(30), MaxConnectionPoolSize = 50, ConnectionAcquisitionTimeout = TimeSpan.FromMinutes(2) }); } // end::config-connection-pool[] [RequireServerFact] public void TestConfigConnectionPoolExample() { // Given using (var driver = CreateDriverWithCustomizedConnectionPool(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class ConfigConnectionTimeoutExample : BaseExample { public ConfigConnectionTimeoutExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::config-connection-timeout[] public IDriver CreateDriverWithCustomizedConnectionTimeout(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password), new Config {ConnectionTimeout = TimeSpan.FromSeconds(15)}); } // end::config-connection-timeout[] [RequireServerFact] public void TestConfigConnectionTimeoutExample() { // Given using (var driver = CreateDriverWithCustomizedConnectionTimeout(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class ConfigMaxRetryTimeExample : BaseExample { public ConfigMaxRetryTimeExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::config-max-retry-time[] public IDriver CreateDriverWithCustomizedMaxRetryTime(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password), new Config {MaxTransactionRetryTime = TimeSpan.FromSeconds(15)}); } // end::config-max-retry-time[] [RequireServerFact] public void TestConfigMaxRetryTimeExample() { // Given using (var driver = CreateDriverWithCustomizedMaxRetryTime(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class ConfigTrustExample : BaseExample { public ConfigTrustExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::config-trust[] public IDriver CreateDriverWithCustomizedTrustStrategy(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password), new Config {TrustManager = TrustManager.CreateInsecure()}); } // end::config-trust[] [RequireServerFact] public void TestConfigTrustExample() { // Given using (var driver = CreateDriverWithCustomizedTrustStrategy(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class ConfigUnencryptedExample : BaseExample { public ConfigUnencryptedExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::config-unencrypted[] public IDriver CreateDriverWithCustomizedSecurityStrategy(string uri, string user, string password) { return GraphDatabase.Driver(uri, AuthTokens.Basic(user, password), new Config {EncryptionLevel = EncryptionLevel.None}); } // end::config-unencrypted[] [RequireServerFact] public void TestConfigUnencryptedExample() { // Given using (var driver = CreateDriverWithCustomizedSecurityStrategy(Uri, User, Password)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } [SuppressMessage("ReSharper", "xUnit1013")] public class ConfigCustomResolverExample { private const string Username = "neo4j"; private const string Password = "some password"; // tag::config-custom-resolver[] private IDriver CreateDriverWithCustomResolver(string virtualUri, IAuthToken token, params ServerAddress[] addresses) { return GraphDatabase.Driver(virtualUri, token, new Config {Resolver = new ListAddressResolver(addresses), EncryptionLevel = EncryptionLevel.None}); } public void AddPerson(string name) { using (var driver = CreateDriverWithCustomResolver("neo4j://x.acme.com", AuthTokens.Basic(Username, Password), ServerAddress.From("a.acme.com", 7687), ServerAddress.From("b.acme.com", 7877), ServerAddress.From("c.acme.com", 9092))) { using (var session = driver.Session()) { session.Run("CREATE (a:Person {name: $name})", new {name}); } } } private class ListAddressResolver : IServerAddressResolver { private readonly ServerAddress[] servers; public ListAddressResolver(params ServerAddress[] servers) { this.servers = servers; } public ISet<ServerAddress> Resolve(ServerAddress address) { return new HashSet<ServerAddress>(servers); } } // end::config-custom-resolver[] [RequireBoltStubServerFactAttribute] public void TestCustomResolverExample() { using (var server1 = BoltStubServer.Start("V4/get_routing_table_only", 9001)) { using (var server2 = BoltStubServer.Start("V4/return_1", 9002)) { using (var driver = CreateDriverWithCustomResolver("neo4j://x.acme.com", AuthTokens.None, ServerAddress.From("localhost", 9001))) { using (var session = driver.Session(o => o.WithDefaultAccessMode(AccessMode.Read))) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } } } } public class CustomAuthExample : BaseExample { public CustomAuthExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::custom-auth[] public IDriver CreateDriverWithCustomizedAuth(string uri, string principal, string credentials, string realm, string scheme, Dictionary<string, object> parameters) { return GraphDatabase.Driver(uri, AuthTokens.Custom(principal, credentials, realm, scheme, parameters), new Config {EncryptionLevel = EncryptionLevel.None}); } // end::custom-auth[] [RequireServerFact] public void TestCustomAuthExample() { // Given using (var driver = CreateDriverWithCustomizedAuth(Uri, User, Password, "native", "basic", null)) using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class KerberosAuthExample : BaseExample { public KerberosAuthExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::kerberos-auth[] public IDriver CreateDriverWithKerberosAuth(string uri, string ticket) { return GraphDatabase.Driver(uri, AuthTokens.Kerberos(ticket), new Config {EncryptionLevel = EncryptionLevel.None}); } // end::kerberos-auth[] [RequireServerFact] public void TestKerberosAuthExample() { // Given using (var driver = CreateDriverWithKerberosAuth(Uri, "kerberos ticket")) { // When & Then driver.Should().BeOfType<Internal.Driver>(); } } } public class CypherErrorExample : BaseExample { public CypherErrorExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::cypher-error[] public int GetEmployeeNumber(string name) { using (var session = Driver.Session()) { return session.ReadTransaction(tx => SelectEmployee(tx, name)); } } private int SelectEmployee(ITransaction tx, string name) { try { var result = tx.Run("SELECT * FROM Employees WHERE name = $name", new {name}); return result.Single()["employee_number"].As<int>(); } catch (ClientException ex) { Output.WriteLine(ex.Message); return -1; } } // end::cypher-error[] [RequireServerFact] public void TestCypherErrorExample() { // When & Then GetEmployeeNumber("Alice").Should().Be(-1); } } public class DriverLifecycleExampleTest : BaseExample { public DriverLifecycleExampleTest(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::driver-lifecycle[] public class DriverLifecycleExample : IDisposable { public IDriver Driver { get; } public DriverLifecycleExample(string uri, string user, string password) { Driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password)); } public void Dispose() { Driver?.Dispose(); } } // end::driver-lifecycle[] [RequireServerFact] public void TestDriverLifecycleExample() { // Given var driver = new DriverLifecycleExample(Uri, User, Password).Driver; using (var session = driver.Session()) { // When & Then session.Run("RETURN 1").Single()[0].As<int>().Should().Be(1); } } } public class HelloWorldExampleTest : BaseExample { public HelloWorldExampleTest(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } [RequireServerFact] public void TestHelloWorldExample() { // Given using (var example = new HelloWorldExample(Uri, User, Password)) { // When & Then example.PrintGreeting("Hello, world"); } } // tag::hello-world[] public class HelloWorldExample : IDisposable { private readonly IDriver _driver; public HelloWorldExample(string uri, string user, string password) { _driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password)); } public void PrintGreeting(string message) { using (var session = _driver.Session()) { var greeting = session.WriteTransaction(tx => { var result = tx.Run("CREATE (a:Greeting) " + "SET a.message = $message " + "RETURN a.message + ', from node ' + id(a)", new {message}); return result.Single()[0].As<string>(); }); Console.WriteLine(greeting); } } public void Dispose() { _driver?.Dispose(); } public static void Main() { using (var greeter = new HelloWorldExample("bolt://localhost:7687", "neo4j", "password")) { greeter.PrintGreeting("hello, world"); } } } // end::hello-world[] } public class ReadWriteTransactionExample : BaseExample { public ReadWriteTransactionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } [RequireServerFact] public void TestReadWriteTransactionExample() { // When & Then AddPerson("Alice").Should().BeGreaterOrEqualTo(0L); } // tag::read-write-transaction[] public long AddPerson(string name) { using (var session = Driver.Session()) { session.WriteTransaction(tx => CreatePersonNode(tx, name)); return session.ReadTransaction(tx => MatchPersonNode(tx, name)); } } private static IStatementResult CreatePersonNode(ITransaction tx, string name) { return tx.Run("CREATE (a:Person {name: $name})", new {name}); } private static long MatchPersonNode(ITransaction tx, string name) { var result = tx.Run("MATCH (a:Person {name: $name}) RETURN id(a)", new {name}); return result.Single()[0].As<long>(); } // end::read-write-transaction[] } public class ResultConsumeExample : BaseExample { public ResultConsumeExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::result-consume[] public List<string> GetPeople() { using (var session = Driver.Session()) { return session.ReadTransaction(tx => { var result = tx.Run("MATCH (a:Person) RETURN a.name ORDER BY a.name"); return result.Select(record => record[0].As<string>()).ToList(); }); } } // end::result-consume[] [RequireServerFact] public void TestResultConsumeExample() { // Given Write("CREATE (a:Person {name: 'Alice'})"); Write("CREATE (a:Person {name: 'Bob'})"); // When & Then GetPeople().Should().Contain(new[] {"Alice", "Bob"}); } } public class ResultRetainExample : BaseExample { public ResultRetainExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::result-retain[] public int AddEmployees(string companyName) { using (var session = Driver.Session()) { var persons = session.ReadTransaction(tx => tx.Run("MATCH (a:Person) RETURN a.name AS name").ToList()); return persons.Sum(person => session.WriteTransaction(tx => { tx.Run("MATCH (emp:Person {name: $person_name}) " + "MERGE (com:Company {name: $company_name}) " + "MERGE (emp)-[:WORKS_FOR]->(com)", new {person_name = person["name"].As<string>(), company_name = companyName}); return 1; })); } } // end::result-retain[] [RequireServerFact] public void TestResultConsumeExample() { // Given Write("CREATE (a:Person {name: 'Alice'})"); Write("CREATE (a:Person {name: 'Bob'})"); // When & Then AddEmployees("Acme").Should().Be(2); Read("MATCH (emp:Person)-[WORKS_FOR]->(com:Company) WHERE com.name = 'Acme' RETURN count(emp)") .Single()[0].As<int>().Should().Be(2); } } public class ServiceUnavailableExample : BaseExample { private readonly IDriver _baseDriver; public ServiceUnavailableExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { _baseDriver = Driver; Driver = GraphDatabase.Driver("bolt://localhost:8080", AuthTokens.Basic(User, Password), new Config {MaxTransactionRetryTime = TimeSpan.FromSeconds(3)}); } protected override void Dispose(bool isDisposing) { if (!isDisposing) return; Driver = _baseDriver; base.Dispose(true); } // tag::service-unavailable[] public bool AddItem() { try { using (var session = Driver.Session()) { return session.WriteTransaction( tx => { tx.Run("CREATE (a:Item)"); return true; } ); } } catch (ServiceUnavailableException) { return false; } } // end::service-unavailable[] [RequireServerFact] public void TestServiceUnavailableExample() { AddItem().Should().BeFalse(); } } [SuppressMessage("ReSharper", "xUnit1013")] public class SessionExample : BaseExample { public SessionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::session[] public void AddPerson(string name) { using (var session = Driver.Session()) { session.Run("CREATE (a:Person {name: $name})", new {name}); } } // end::session[] [RequireServerFact] public void TestSessionExample() { // Given & When AddPerson("Alice"); // Then CountPerson("Alice").Should().Be(1); } } [SuppressMessage("ReSharper", "xUnit1013")] public class TransactionFunctionExample : BaseExample { public TransactionFunctionExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::transaction-function[] public void AddPerson(string name) { using (var session = Driver.Session()) { session.WriteTransaction(tx => tx.Run("CREATE (a:Person {name: $name})", new {name})); } } // end::transaction-function[] [RequireServerFact] public void TestTransactionFunctionExample() { // Given & When AddPerson("Alice"); // Then CountPerson("Alice").Should().Be(1); } } [SuppressMessage("ReSharper", "xUnit1013")] public class PassBookmarksExample : BaseExample { public PassBookmarksExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) : base(output, fixture) { } // tag::pass-bookmarks[] // Create a company node private IStatementResult AddCompany(ITransaction tx, string name) { return tx.Run("CREATE (a:Company {name: $name})", new {name}); } // Create a person node private IStatementResult AddPerson(ITransaction tx, string name) { return tx.Run("CREATE (a:Person {name: $name})", new {name}); } // Create an employment relationship to a pre-existing company node. // This relies on the person first having been created. private IStatementResult Employ(ITransaction tx, string personName, string companyName) { return tx.Run(@"MATCH (person:Person {name: $personName}) MATCH (company:Company {name: $companyName}) CREATE (person)-[:WORKS_FOR]->(company)", new {personName, companyName}); } // Create a friendship between two people. private IStatementResult MakeFriends(ITransaction tx, string name1, string name2) { return tx.Run(@"MATCH (a:Person {name: $name1}) MATCH (b:Person {name: $name2}) MERGE (a)-[:KNOWS]->(b)", new {name1, name2}); } // Match and display all friendships. private int PrintFriendships(ITransaction tx) { var result = tx.Run("MATCH (a)-[:KNOWS]->(b) RETURN a.name, b.name"); var count = 0; foreach (var record in result) { count++; Console.WriteLine($"{record["a.name"]} knows {record["b.name"]}"); } return count; } public void AddEmployAndMakeFriends() { // To collect the session bookmarks var savedBookmarks = new List<Bookmark>(); // Create the first person and employment relationship. using (var session1 = Driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write))) { session1.WriteTransaction(tx => AddCompany(tx, "Wayne Enterprises")); session1.WriteTransaction(tx => AddPerson(tx, "Alice")); session1.WriteTransaction(tx => Employ(tx, "Alice", "Wayne Enterprises")); savedBookmarks.Add(session1.LastBookmark); } // Create the second person and employment relationship. using (var session2 = Driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write))) { session2.WriteTransaction(tx => AddCompany(tx, "LexCorp")); session2.WriteTransaction(tx => AddPerson(tx, "Bob")); session2.WriteTransaction(tx => Employ(tx, "Bob", "LexCorp")); savedBookmarks.Add(session2.LastBookmark); } // Create a friendship between the two people created above. using (var session3 = Driver.Session(o => o.WithDefaultAccessMode(AccessMode.Write).WithBookmarks(savedBookmarks.ToArray()))) { session3.WriteTransaction(tx => MakeFriends(tx, "Alice", "Bob")); session3.ReadTransaction(PrintFriendships); } } // end::pass-bookmarks[] [RequireServerFact] public void TestPassBookmarksExample() { // Given & When AddEmployAndMakeFriends(); // Then CountNodes("Person", "name", "Alice").Should().Be(1); CountNodes("Person", "name", "Bob").Should().Be(1); CountNodes("Company", "name", "Wayne Enterprises").Should().Be(1); CountNodes("Company", "name", "LexCorp").Should().Be(1); var works1 = Read( "MATCH (a:Person {name: $person})-[:WORKS_FOR]->(b:Company {name: $company}) RETURN count(a)", new {person = "Alice", company = "Wayne Enterprises"}); works1.Count().Should().Be(1); var works2 = Read( "MATCH (a:Person {name: $person})-[:WORKS_FOR]->(b:Company {name: $company}) RETURN count(a)", new {person = "Bob", company = "LexCorp"}); works2.Count().Should().Be(1); var friends = Read( "MATCH (a:Person {name: $person1})-[:KNOWS]->(b:Person {name: $person2}) RETURN count(a)", new {person1 = "Alice", person2 = "Bob"}); friends.Count().Should().Be(1); } } } [Collection(SAIntegrationCollection.CollectionName)] public abstract class BaseExample : IDisposable { protected ITestOutputHelper Output { get; } protected IDriver Driver { set; get; } protected const string Uri = "bolt://localhost:7687"; protected const string User = "neo4j"; protected const string Password = "neo4j"; protected BaseExample(ITestOutputHelper output, StandAloneIntegrationTestFixture fixture) { Output = output; Driver = fixture.StandAlone.Driver; } protected virtual void Dispose(bool isDisposing) { if (!isDisposing) return; using (var session = Driver.Session()) { session.Run("MATCH (n) DETACH DELETE n").Consume(); } } public void Dispose() { Dispose(true); } protected int CountNodes(string label, string property, string value) { using (var session = Driver.Session()) { return session.ReadTransaction( tx => tx.Run($"MATCH (a:{label} {{{property}: $value}}) RETURN count(a)", new {value}).Single()[0].As<int>()); } } protected int CountPerson(string name) { return CountNodes("Person", "name", name); } protected void Write(string statement, object parameters = null) { using (var session = Driver.Session()) { session.WriteTransaction(tx => tx.Run(statement, parameters)); } } protected IStatementResult Read(string statement, object parameters = null) { using (var session = Driver.Session()) { return session.ReadTransaction(tx => tx.Run(statement, parameters)); } } } // TODO Remove it after we figure out a way to solve the naming problem internal static class ValueExtensions { public static T As<T>(this object value) { return Neo4j.Driver.ValueExtensions.As<T>(value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using HttpClientGenerator.ClientGenerationModel; using HttpClientGenerator.References; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using RestSharp; namespace HttpClientGenerator { internal class ClientEmitter { private readonly IEnumerable<ClientInfo> _endpoints; private readonly IEnumerable<SimpleType> _collectParameterSimpleTypes; private Lazy<SyntaxTree> tree; private ClientEmitter(IEnumerable<ClientInfo> endpoints, IEnumerable<SimpleType> collectParameterSimpleTypes) { _endpoints = endpoints; _collectParameterSimpleTypes = collectParameterSimpleTypes; tree = new Lazy<SyntaxTree>(() => CreateSyntaxTree(_endpoints, _collectParameterSimpleTypes)); } private static SyntaxTree CreateSyntaxTree(IEnumerable<ClientInfo> endpoints, IEnumerable<SimpleType> collectedSimpleTypes) { var types = endpoints.Select(EmitClass).ToArray<MemberDeclarationSyntax>(); var clientNamespace = SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName("Clients")) .AddMembers(types) .AddMembers(CreateSimpleTypes(collectedSimpleTypes).ToArray<MemberDeclarationSyntax>()); var unit = SyntaxFactory.CompilationUnit() .AddUsings( SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(RestClient).Namespace)), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(IEnumerable<>).Namespace)), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(typeof(Guid).Namespace))) .AddMembers(clientNamespace); return SyntaxFactory.SyntaxTree(unit); } private static IEnumerable<ClassDeclarationSyntax> CreateSimpleTypes(IEnumerable<SimpleType> collectedSimpleTypes) { return collectedSimpleTypes.Select(EmitSimpleClass); } private static ClassDeclarationSyntax EmitSimpleClass(SimpleType ty) { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); return SyntaxFactory.ClassDeclaration(ty.Name) .AddMembers(EmitTypeProperties(ty).ToArray<MemberDeclarationSyntax>()) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .WithLeadingTrivia(newlineTrivia) .WithTrailingTrivia(newlineTrivia); } private static IEnumerable<PropertyDeclarationSyntax> EmitTypeProperties(SimpleType ty) { return ty.Members.Select(EmitSimpleTypeProperty); } private static PropertyDeclarationSyntax EmitSimpleTypeProperty(SimpleTypeMember mem) { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); return SyntaxFactory.PropertyDeclaration(SyntaxFactory.ParseTypeName(mem.TypeName), mem.Name) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddAccessorListAccessors( SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)) .WithLeadingTrivia(newlineTrivia) .WithTrailingTrivia(newlineTrivia); } private static ClassDeclarationSyntax EmitClass(ClientInfo clientInfo) { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); return SyntaxFactory.ClassDeclaration(clientInfo.ClientName) .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) .AddBaseListTypes(SyntaxFactory.ParseTypeName(typeof(RestClient).FullName)) .AddMembers(EmitMembers(clientInfo.RestEndpoints)) .AddMembers(EmitConstructor()) .WithLeadingTrivia(newlineTrivia) .WithTrailingTrivia(newlineTrivia); } private static MemberDeclarationSyntax EmitConstructor() { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); return SyntaxFactory.ConstructorDeclaration(".ctor") .WithParameterList(SyntaxFactory.ParseParameterList("(string baseUri)")) .WithInitializer( SyntaxFactory.ConstructorInitializer( kind: SyntaxKind.BaseConstructorInitializer, argumentList: SyntaxFactory.ParseArgumentList("(baseUri)"))) .WithBody(SyntaxFactory.Block()) .WithLeadingTrivia(newlineTrivia, newlineTrivia) .WithTrailingTrivia(newlineTrivia); } private static MemberDeclarationSyntax[] EmitMembers(IEnumerable<RestEndpointInfo> restEndpoints) { return restEndpoints.Select(GenerateMethod).ToArray<MemberDeclarationSyntax>(); } private static MethodDeclarationSyntax GenerateMethod(RestEndpointInfo restEndpointInfo) { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); TypeSyntax returnType; if (restEndpointInfo.ReturnType != "void") { returnType = SyntaxFactory.GenericName("System.Threading.Tasks.Task") .WithTypeArgumentList( SyntaxFactory.TypeArgumentList() .AddArguments(SyntaxFactory.ParseTypeName(restEndpointInfo.ReturnType))); } else { returnType = SyntaxFactory.ParseTypeName("System.Threading.Tasks.Task"); } return SyntaxFactory.MethodDeclaration(returnType, restEndpointInfo.Name) .AddParameterListParameters(restEndpointInfo.Parameters.Select(GenerateParameter).ToArray()) .AddBodyStatements(GenerateMethodBody(restEndpointInfo)) .WithTrailingTrivia(newlineTrivia).WithLeadingTrivia(newlineTrivia); } private static StatementSyntax[] GenerateMethodBody(RestEndpointInfo restEndpointInfo) { var newlineTrivia = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, "\r\n"); var nullExpression = SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression) .WithLeadingTrivia(SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " ")); return new StatementSyntax[] { SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName(typeof(RestRequest).FullName), SyntaxFactory.SeparatedList<VariableDeclaratorSyntax>() .Add( SyntaxFactory.VariableDeclarator("@_request") .WithInitializer( SyntaxFactory.EqualsValueClause( SyntaxFactory.ObjectCreationExpression(SyntaxFactory.ParseTypeName(typeof(RestRequest).FullName)) .AddArgumentListArguments( SyntaxFactory.Argument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(restEndpointInfo.Uri))), SyntaxFactory.Argument( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseTypeName(typeof(Method).FullName), SyntaxFactory.IdentifierName(restEndpointInfo.Method.ToString()))))))))), SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.GenericName("Execute") .AddTypeArgumentListArguments(SyntaxFactory.ParseTypeName("object"))) .AddArgumentListArguments(SyntaxFactory.Argument(SyntaxFactory.IdentifierName("@_request")))) .WithTrailingTrivia(newlineTrivia) .WithLeadingTrivia(newlineTrivia), SyntaxFactory.ReturnStatement(nullExpression) .WithTrailingTrivia(newlineTrivia) }; } private static ParameterSyntax GenerateParameter(EndpointParameter endpointParameter) { return SyntaxFactory.Parameter(SyntaxFactory.Identifier(endpointParameter.Name)) .WithType(SyntaxFactory.ParseTypeName(endpointParameter.TypeName)); } public void DumpTree() { Console.WriteLine(tree.Value); } public static ClientEmitter WithEndpoints(IEnumerable<ClientInfo> endpoints, IEnumerable<SimpleType> collectParameterSimpleTypes) { return new ClientEmitter(endpoints, collectParameterSimpleTypes); } public CSharpCompilation CreateCompilation(ReferenceCache referenceCache) { return CSharpCompilation.Create( "Clients", syntaxTrees: new[] { tree.Value }, references: new[] { referenceCache.MSCoreLib, referenceCache.SystemRuntime, referenceCache.AssemblyReferenceForType<HttpClient>(), referenceCache.AssemblyReferenceForType<RestClient>(), referenceCache.AssemblyReferenceForType<Uri>(), //referenceCache.ForAssemblyLocation(@"C:\pf\Stash\aco\Composite\Core\bin\Debug\PF.Aco.Entities.dll") }, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); } } }
using System.Collections.Generic; using Mod; using UnityEngine; namespace Photon { public class PhotonStream { private byte currentItem; internal List<object> data; private bool write; public PhotonStream(bool write, object[] incomingData) { this.write = write; if (incomingData == null) { this.data = new List<object>(); } else { this.data = new List<object>(incomingData); } } public object ReceiveNext() { if (this.write) { Debug.LogError("Error: you cannot read this stream that you are writing!"); return null; } if (currentItem > data.Count - 1) return null; object obj2 = this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); return obj2; } public void SendNext(object obj) { if (!this.write) { Debug.LogError("Error: you cannot write/send to this stream that you are reading!"); } else { this.data.Add(obj); } } public void Serialize(ref Player obj) { if (this.write) { this.data.Add(obj); } else if (this.data.Count > this.currentItem) { obj = (Player) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref bool myBool) { if (this.write) { this.data.Add(myBool); } else if (this.data.Count > this.currentItem) { myBool = (bool) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref char value) { if (this.write) { this.data.Add(value); } else if (this.data.Count > this.currentItem) { value = (char) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref short value) { if (this.write) { this.data.Add(value); } else if (this.data.Count > this.currentItem) { value = (short) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref int myInt) { if (this.write) { this.data.Add(myInt); } else if (this.data.Count > this.currentItem) { myInt = (int) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref float obj) { if (this.write) { this.data.Add(obj); } else if (this.data.Count > this.currentItem) { obj = (float) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref string value) { if (this.write) { this.data.Add(value); } else if (this.data.Count > this.currentItem) { value = (string) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref Quaternion obj) { if (this.write) { this.data.Add(obj); } else if (this.data.Count > this.currentItem) { obj = (Quaternion) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref Vector2 obj) { if (this.write) { this.data.Add(obj); } else if (this.data.Count > this.currentItem) { obj = (Vector2) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public void Serialize(ref Vector3 obj) { if (this.write) { this.data.Add(obj); } else if (this.data.Count > this.currentItem) { obj = (Vector3) this.data[this.currentItem]; this.currentItem = (byte) (this.currentItem + 1); } } public object[] ToArray() { return this.data.ToArray(); } public int Count { get { return this.data.Count; } } public bool isReading { get { return !this.write; } } public bool isWriting { get { return this.write; } } } }
/* * 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 log4net.Config; using Nini.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.CoreModules.Avatar.Chat; using OpenSim.Region.CoreModules.Framework; using OpenSim.Region.CoreModules.Framework.EntityTransfer; using OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Tests.Common; namespace OpenSim.Region.CoreModules.Avatar.Chat.Tests { [TestFixture] public class ChatModuleTests : OpenSimTestCase { [TestFixtureSetUp] public void FixtureInit() { // Don't allow tests to be bamboozled by asynchronous events. Execute everything on the same thread. // We must do this here so that child agent positions are updated in a predictable manner. Util.FireAndForgetMethod = FireAndForgetMethod.RegressionTest; } [TestFixtureTearDown] public void TearDown() { // We must set this back afterwards, otherwise later tests will fail since they're expecting multiple // threads. Possibly, later tests should be rewritten so none of them require async stuff (which regression // tests really shouldn't). Util.FireAndForgetMethod = Util.DefaultFireAndForgetMethod; } private void SetupNeighbourRegions(TestScene sceneA, TestScene sceneB) { // XXX: HTTP server is not (and should not be) necessary for this test, though it's absence makes the // CapabilitiesModule complain when it can't set up HTTP endpoints. // BaseHttpServer httpServer = new BaseHttpServer(99999); // MainServer.AddHttpServer(httpServer); // MainServer.Instance = httpServer; // We need entity transfer modules so that when sp2 logs into the east region, the region calls // EntityTransferModuleto set up a child agent on the west region. // XXX: However, this is not an entity transfer so is misleading. EntityTransferModule etmA = new EntityTransferModule(); EntityTransferModule etmB = new EntityTransferModule(); LocalSimulationConnectorModule lscm = new LocalSimulationConnectorModule(); IConfigSource config = new IniConfigSource(); config.AddConfig("Chat"); IConfig modulesConfig = config.AddConfig("Modules"); modulesConfig.Set("EntityTransferModule", etmA.Name); modulesConfig.Set("SimulationServices", lscm.Name); SceneHelpers.SetupSceneModules(new Scene[] { sceneA, sceneB }, config, lscm); SceneHelpers.SetupSceneModules(sceneA, config, new CapabilitiesModule(), etmA, new ChatModule()); SceneHelpers.SetupSceneModules(sceneB, config, new CapabilitiesModule(), etmB, new ChatModule()); } /// <summary> /// Tests chat between neighbour regions on the east-west axis /// </summary> /// <remarks> /// Really, this is a combination of a child agent position update test and a chat range test. These need /// to be separated later on. /// </remarks> [Test] public void TestInterRegionChatDistanceEastWest() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID sp1Uuid = TestHelpers.ParseTail(0x11); UUID sp2Uuid = TestHelpers.ParseTail(0x12); Vector3 sp1Position = new Vector3(6, 128, 20); Vector3 sp2Position = new Vector3(250, 128, 20); SceneHelpers sh = new SceneHelpers(); TestScene sceneWest = sh.SetupScene("sceneWest", TestHelpers.ParseTail(0x1), 1000, 1000); TestScene sceneEast = sh.SetupScene("sceneEast", TestHelpers.ParseTail(0x2), 1001, 1000); SetupNeighbourRegions(sceneWest, sceneEast); ScenePresence sp1 = SceneHelpers.AddScenePresence(sceneEast, sp1Uuid); TestClient sp1Client = (TestClient)sp1.ControllingClient; // If we don't set agents to flying, test will go wrong as they instantly fall to z = 0. // TODO: May need to create special complete no-op test physics module rather than basic physics, since // physics is irrelevant to this test. sp1.Flying = true; // When sp1 logs in to sceneEast, it sets up a child agent in sceneWest and informs the sp2 client to // make the connection. For this test, will simplify this chain by making the connection directly. ScenePresence sp1Child = SceneHelpers.AddChildScenePresence(sceneWest, sp1Uuid); TestClient sp1ChildClient = (TestClient)sp1Child.ControllingClient; sp1.AbsolutePosition = sp1Position; ScenePresence sp2 = SceneHelpers.AddScenePresence(sceneWest, sp2Uuid); TestClient sp2Client = (TestClient)sp2.ControllingClient; sp2.Flying = true; ScenePresence sp2Child = SceneHelpers.AddChildScenePresence(sceneEast, sp2Uuid); TestClient sp2ChildClient = (TestClient)sp2Child.ControllingClient; sp2.AbsolutePosition = sp2Position; // We must update the scenes in order to make the root new root agents trigger position updates in their // children. sceneWest.Update(1); sceneEast.Update(1); // Check child positions are correct. Assert.AreEqual( new Vector3(sp1Position.X + sceneEast.RegionInfo.RegionSizeX, sp1Position.Y, sp1Position.Z), sp1ChildClient.SceneAgent.AbsolutePosition); Assert.AreEqual( new Vector3(sp2Position.X - sceneWest.RegionInfo.RegionSizeX, sp2Position.Y, sp2Position.Z), sp2ChildClient.SceneAgent.AbsolutePosition); string receivedSp1ChatMessage = ""; string receivedSp2ChatMessage = ""; sp1ChildClient.OnReceivedChatMessage += (message, type, fromPos, fromName, fromAgentID, ownerID, source, audible) => receivedSp1ChatMessage = message; sp2ChildClient.OnReceivedChatMessage += (message, type, fromPos, fromName, fromAgentID, ownerID, source, audible) => receivedSp2ChatMessage = message; TestUserInRange(sp1Client, "ello darling", ref receivedSp2ChatMessage); TestUserInRange(sp2Client, "fantastic cats", ref receivedSp1ChatMessage); sp1Position = new Vector3(30, 128, 20); sp1.AbsolutePosition = sp1Position; sceneEast.Update(1); // Check child position is correct. Assert.AreEqual( new Vector3(sp1Position.X + sceneEast.RegionInfo.RegionSizeX, sp1Position.Y, sp1Position.Z), sp1ChildClient.SceneAgent.AbsolutePosition); TestUserOutOfRange(sp1Client, "beef", ref receivedSp2ChatMessage); TestUserOutOfRange(sp2Client, "lentils", ref receivedSp1ChatMessage); } /// <summary> /// Tests chat between neighbour regions on the north-south axis /// </summary> /// <remarks> /// Really, this is a combination of a child agent position update test and a chat range test. These need /// to be separated later on. /// </remarks> [Test] public void TestInterRegionChatDistanceNorthSouth() { TestHelpers.InMethod(); // TestHelpers.EnableLogging(); UUID sp1Uuid = TestHelpers.ParseTail(0x11); UUID sp2Uuid = TestHelpers.ParseTail(0x12); Vector3 sp1Position = new Vector3(128, 250, 20); Vector3 sp2Position = new Vector3(128, 6, 20); SceneHelpers sh = new SceneHelpers(); TestScene sceneNorth = sh.SetupScene("sceneNorth", TestHelpers.ParseTail(0x1), 1000, 1000); TestScene sceneSouth = sh.SetupScene("sceneSouth", TestHelpers.ParseTail(0x2), 1000, 1001); SetupNeighbourRegions(sceneNorth, sceneSouth); ScenePresence sp1 = SceneHelpers.AddScenePresence(sceneNorth, sp1Uuid); TestClient sp1Client = (TestClient)sp1.ControllingClient; // If we don't set agents to flying, test will go wrong as they instantly fall to z = 0. // TODO: May need to create special complete no-op test physics module rather than basic physics, since // physics is irrelevant to this test. sp1.Flying = true; // When sp1 logs in to sceneEast, it sets up a child agent in sceneNorth and informs the sp2 client to // make the connection. For this test, will simplify this chain by making the connection directly. ScenePresence sp1Child = SceneHelpers.AddChildScenePresence(sceneSouth, sp1Uuid); TestClient sp1ChildClient = (TestClient)sp1Child.ControllingClient; sp1.AbsolutePosition = sp1Position; ScenePresence sp2 = SceneHelpers.AddScenePresence(sceneSouth, sp2Uuid); TestClient sp2Client = (TestClient)sp2.ControllingClient; sp2.Flying = true; ScenePresence sp2Child = SceneHelpers.AddChildScenePresence(sceneNorth, sp2Uuid); TestClient sp2ChildClient = (TestClient)sp2Child.ControllingClient; sp2.AbsolutePosition = sp2Position; // We must update the scenes in order to make the root new root agents trigger position updates in their // children. sceneNorth.Update(1); sceneSouth.Update(1); // Check child positions are correct. Assert.AreEqual( new Vector3(sp1Position.X, sp1Position.Y - sceneNorth.RegionInfo.RegionSizeY, sp1Position.Z), sp1ChildClient.SceneAgent.AbsolutePosition); Assert.AreEqual( new Vector3(sp2Position.X, sp2Position.Y + sceneSouth.RegionInfo.RegionSizeY, sp2Position.Z), sp2ChildClient.SceneAgent.AbsolutePosition); string receivedSp1ChatMessage = ""; string receivedSp2ChatMessage = ""; sp1ChildClient.OnReceivedChatMessage += (message, type, fromPos, fromName, fromAgentID, ownerID, source, audible) => receivedSp1ChatMessage = message; sp2ChildClient.OnReceivedChatMessage += (message, type, fromPos, fromName, fromAgentID, ownerID, source, audible) => receivedSp2ChatMessage = message; TestUserInRange(sp1Client, "ello darling", ref receivedSp2ChatMessage); TestUserInRange(sp2Client, "fantastic cats", ref receivedSp1ChatMessage); sp1Position = new Vector3(30, 128, 20); sp1.AbsolutePosition = sp1Position; sceneNorth.Update(1); // Check child position is correct. Assert.AreEqual( new Vector3(sp1Position.X, sp1Position.Y - sceneNorth.RegionInfo.RegionSizeY, sp1Position.Z), sp1ChildClient.SceneAgent.AbsolutePosition); TestUserOutOfRange(sp1Client, "beef", ref receivedSp2ChatMessage); TestUserOutOfRange(sp2Client, "lentils", ref receivedSp1ChatMessage); } private void TestUserInRange(TestClient speakClient, string testMessage, ref string receivedMessage) { receivedMessage = ""; speakClient.Chat(0, ChatTypeEnum.Say, testMessage); Assert.AreEqual(testMessage, receivedMessage); } private void TestUserOutOfRange(TestClient speakClient, string testMessage, ref string receivedMessage) { receivedMessage = ""; speakClient.Chat(0, ChatTypeEnum.Say, testMessage); Assert.AreNotEqual(testMessage, receivedMessage); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using log4net; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenMetaverse.Assets; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public class J2KDecodeFileCache { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly string m_cacheDecodeFolder; private bool enabled = true; /// <summary> /// Temporarily holds deserialized layer data information in memory /// </summary> private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]>(); /// <summary> /// Creates a new instance of a file cache /// </summary> /// <param name="pFolder">base folder for the cache. Will be created if it doesn't exist</param> public J2KDecodeFileCache(bool enabled, string pFolder) { this.enabled = enabled; m_cacheDecodeFolder = pFolder; if ((enabled == true) && (Directory.Exists(pFolder) == false)) { Createj2KCacheFolder(pFolder); } } public static string CacheFolder { get { return Util.dataDir() + "/j2kDecodeCache"; } } /// <summary> /// Save Layers to Disk Cache /// </summary> /// <param name="AssetId">Asset to Save the layers. Used int he file name by default</param> /// <param name="Layers">The Layer Data from OpenJpeg</param> /// <returns></returns> public bool SaveCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { if (Layers.Length > 0) { m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10)); if (enabled == true) { using (FileStream fsCache = new FileStream(String.Format("{0}/{1}", m_cacheDecodeFolder, FileNameFromAssetId(AssetId)), FileMode.Create)) { using (StreamWriter fsSWCache = new StreamWriter(fsCache)) { StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == (Layers.Length - 1)) strEnd = String.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } fsSWCache.Write(stringResult.ToString()); fsSWCache.Close(); return true; } } } } return false; } /// <summary> /// Loads the Layer data from the disk cache /// Returns true if load succeeded /// </summary> /// <param name="AssetId">AssetId that we're checking the cache for</param> /// <param name="Layers">out layers to save to</param> /// <returns>true if load succeeded</returns> public bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { // Check if it's cached in memory if (m_decodedCache.TryGetValue(AssetId, out Layers)) { return true; } // Look for it in the file cache string filename = String.Format("{0}/{1}", m_cacheDecodeFolder, FileNameFromAssetId(AssetId)); Layers = new OpenJPEG.J2KLayerInfo[0]; if ((File.Exists(filename) == false) || (enabled == false)) return false; string readResult = String.Empty; try { using (FileStream fsCachefile = new FileStream(filename, FileMode.Open)) { using (StreamReader sr = new StreamReader(fsCachefile)) { readResult = sr.ReadToEnd(); sr.Close(); } } } catch (IOException ioe) { if (ioe is PathTooLongException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Path is too long."); } else if (ioe is DirectoryNotFoundException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Cache Directory does not exist!"); enabled = false; } else { m_log.Error( "[J2KDecodeCache]: Cache Read failed. IO Exception."); } return false; } catch (UnauthorizedAccessException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. UnauthorizedAccessException Exception. Do you have the proper permissions on this file?"); return false; } catch (ArgumentException ae) { if (ae is ArgumentNullException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed. No Filename provided"); } else { m_log.Error( "[J2KDecodeCache]: Cache Read failed. Filname was invalid"); } return false; } catch (NotSupportedException) { m_log.Error( "[J2KDecodeCache]: Cache Read failed, not supported. Cache disabled!"); enabled = false; return false; } catch (Exception e) { m_log.ErrorFormat( "[J2KDecodeCache]: Cache Read failed, unknown exception. Error: {0}", e.ToString()); return false; } string[] lines = readResult.Split('\n'); if (lines.Length <= 0) return false; Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed with ErrorConvert for {0}", AssetId); Layers = new OpenJPEG.J2KLayerInfo[0]; return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { // reading failed m_log.WarnFormat("[J2KDecodeCache]: Cache Read failed for {0}", AssetId); Layers = new OpenJPEG.J2KLayerInfo[0]; return false; } } return true; } /// <summary> /// Routine which converts assetid to file name /// </summary> /// <param name="AssetId">asset id of the image</param> /// <returns>string filename</returns> public string FileNameFromAssetId(UUID AssetId) { return String.Format("j2kCache_{0}.cache", AssetId); } /// <summary> /// Creates the Cache Folder /// </summary> /// <param name="pFolder">Folder to Create</param> public void Createj2KCacheFolder(string pFolder) { try { Directory.CreateDirectory(pFolder); } catch (IOException ioe) { if (ioe is PathTooLongException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the path to the cache folder is too long. Cache disabled!"); } else if (ioe is DirectoryNotFoundException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the supplied base of the directory folder does not exist. Cache disabled!"); } else { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an IO Exception. Cache disabled!"); } enabled = false; } catch (UnauthorizedAccessException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an UnauthorizedAccessException Exception. Cache disabled!"); enabled = false; } catch (ArgumentException ae) { if (ae is ArgumentNullException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because the folder provided is invalid! Cache disabled!"); } else { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because no cache folder was provided! Cache disabled!"); } enabled = false; } catch (NotSupportedException) { m_log.Error( "[J2KDecodeCache]: Cache Directory does not exist and create failed because it's not supported. Cache disabled!"); enabled = false; } catch (Exception e) { m_log.ErrorFormat( "[J2KDecodeCache]: Cache Directory does not exist and create failed because of an unknown exception. Cache disabled! Error: {0}", e.ToString()); enabled = false; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace Piglet.Lexer.Construction { internal class DFA : FiniteAutomata<DFA.State> { public class State : BaseState { public ISet<NFA.State> NfaStates { get; private set; } public bool Mark { get; set; } public State(ISet<NFA.State> nfaStates) { NfaStates = nfaStates; } public IEnumerable<CharRange> LegalMoves(Transition<NFA.State>[] fromTransitions) { return fromTransitions.SelectMany(f => f.ValidInput.Ranges).Distinct(); } public override string ToString() { // Purely for debugging purposes return string.Format( "{0} {{{1}}}", StateNumber, String.Join( ", ", NfaStates)); } public override bool AcceptState { get { return NfaStates.Any(f=>f.AcceptState); } set {} // Do nothing, cannot set } } public static DFA Create(NFA nfa) { var closures = nfa.GetAllClosures(); // The valid input ranges that the NFA contains will need to be split up so that // the smallest possible units which NEVER overlaps will be contained in each of the // states nfa.DistinguishValidInputs(); // Get the closure set of S0 var dfa = new DFA(); dfa.States.Add(new State(closures[nfa.StartState])); while (true) { // Get an unmarked state in dfaStates var t = dfa.States.FirstOrDefault(f => !f.Mark); if (null == t) { // We're done! break; } t.Mark = true; // Get the move states by stimulating this DFA state with // all possible characters. var fromTransitions = nfa.Transitions.Where(f => t.NfaStates.Contains(f.From)).ToArray(); var moveDestinations = new Dictionary<CharRange, List<NFA.State>>(); foreach (var fromTransition in fromTransitions) { foreach (var range in fromTransition.ValidInput.Ranges) { List<NFA.State> destList; if (!moveDestinations.TryGetValue(range, out destList)) { destList = new List<NFA.State>(); moveDestinations.Add(range, destList); } destList.Add(fromTransition.To); } } foreach (CharRange c in t.LegalMoves(fromTransitions)) { var moveSet = moveDestinations[c]; if (moveSet.Any()) { // Get the closure of the move set. This is the NFA states that will form the new set ISet<NFA.State> moveClosure = new HashSet<NFA.State>(); foreach (var moveState in moveSet) { moveClosure.UnionWith(closures[moveState]); } var newState = new State(moveClosure); // See if the new state already exists. If so change the reference to point to // the already created object, since we will need to add a transition back to the same object var oldState = dfa.States.FirstOrDefault(f => f.NfaStates.SetEquals(newState.NfaStates));/* f.NfaStates.Count == newState.NfaStates.Count && !f.NfaStates.Except(newState.NfaStates).Any() && !newState.NfaStates.Except(f.NfaStates).Any());*/ if (oldState == null) { dfa.States.Add(newState); } else { // New state wasn't that new. We already have one exacly like it in the DFA. Set // netstate to oldstate so that the created transition will be correct (still need to // create a transition) newState = oldState; } // See if there already is a transition. In that case, add our character to the list // of valid values var transition = dfa.Transitions.SingleOrDefault(f => f.From == t && f.To == newState); if (transition == null) { // No transition has been found. Create a new one. transition = new Transition<State>(t, newState); dfa.Transitions.Add(transition); } transition.ValidInput.AddRange(c.From, c.To, false); } } } dfa.StartState = dfa.States[0]; dfa.AssignStateNumbers(); return dfa; } public void Minimize() { var distinct = new TriangularTable<int, State>(States.Count, f => f.StateNumber ); distinct.Fill(-1); // Fill with empty states // Create a function for the distinct state pairs and performing an action on them Action<Action<State, State>> distinctStatePairs = action => { for (int i = 0; i < States.Count; ++i) { var p = States[i]; for (int j = i + 1; j < States.Count; ++j) { var q = States[j]; action(p, q); } } }; // Get a set of all valid input ranges that we have in the DFA ISet<CharRange> allValidInputs = new HashSet<CharRange>(); foreach (var transition in Transitions) { allValidInputs.UnionWith(transition.ValidInput.Ranges); } // For every distinct pair of states, if one of them is an accepting state // and the other one is not set the distinct distinctStatePairs((p, q) => { var pIsAcceptState = p.AcceptState; var bIsAcceptState = q.AcceptState; if (bIsAcceptState && pIsAcceptState) { // If both are accepting states, then we might have an issue merging them. // this is because we use multiple regular expressions with different endings when // constructing lexers. var pAcceptStates = p.NfaStates.Where(f => f.AcceptState).ToList(); var qAcceptStates = q.NfaStates.Where(f => f.AcceptState).ToList(); if (pAcceptStates.Count() == qAcceptStates.Count()) { foreach (var pAcceptState in pAcceptStates) { if (!qAcceptStates.Contains(pAcceptState)) { // Since the accepting states differ, its not cool to merge // these two states. distinct[p, q] = int.MaxValue; } } } else { // Not the same number of states, not cool to merge distinct[p, q] = int.MaxValue; } } if (pIsAcceptState ^ bIsAcceptState) { distinct[p, q] = int.MaxValue; } }); // Make a dictionary of from transitions. This is well worth the time, since // this gets accessed lots of times. var targetDict = new Dictionary<State, Dictionary<CharRange, State>>(); foreach (var transition in Transitions) { Dictionary<CharRange, State> toDict; targetDict.TryGetValue(transition.From, out toDict); if (toDict == null) { toDict = new Dictionary<CharRange, State>(); targetDict.Add(transition.From, toDict); } foreach (var range in transition.ValidInput.Ranges) { toDict.Add(range, transition.To); } } // Start iterating bool changes; do { changes = false; distinctStatePairs((p, q) => { if (distinct[p, q] == -1) { Func<State, CharRange, State> targetState = (state, c) => { Dictionary<CharRange, State> charDict; if (targetDict.TryGetValue(state, out charDict)) { State toState; if (charDict.TryGetValue(c, out toState)) { return toState; } } return null; }; foreach (var a in allValidInputs) { var qa = targetState(q, a); var pa = targetState(p, a); if (pa == null ^ qa == null) { // If one of them has a transition on this character range but the other one doesn't then // they are separate. distinct[p, q] = a.GetHashCode(); changes = true; break; } // If both are null, then we carry on. // The other one is null implictly since we have XOR checked it earlier if (qa == null) continue; if (distinct[qa, pa] != -1) { distinct[p, q] = a.GetHashCode(); changes = true; break; } } } }); } while (changes); // Merge states that still have blank square // To make this work we have to bunch states together since the indices will be screwed up var mergeSets = new List<ISet<State>>(); Func<State, ISet<State>> findMergeList = s => mergeSets.FirstOrDefault(m => m.Contains(s)); distinctStatePairs((p, q) => { // No need to check those that we have already determined to be distinct if (distinct[p, q] != -1) return; // These two states are supposed to merge! // See if p or q is already part of a merge list! var pMergeSet = findMergeList(p); var qMergeSet = findMergeList(q); if (pMergeSet == null && qMergeSet == null) { // No previous set for either // Add a new merge set mergeSets.Add(new HashSet<State> { p, q }); } else if (pMergeSet != null && qMergeSet == null) { // Add q to pMergeSet pMergeSet.Add(q); } else if (pMergeSet == null) { // Add p to qMergeSet qMergeSet.Add(p); } else { // Both previously have merge sets // If its not the same set (which it shoudln't be) then add their union if (pMergeSet != qMergeSet) { // Union everything into the pMergeSet pMergeSet.UnionWith(qMergeSet); // Remove the qMergeSet mergeSets.Remove(qMergeSet); } } }); // Armed with the merge sets, we can now do the actual merge foreach (var mergeSet in mergeSets) { // The lone state that should remain is the FIRST set in the mergeset var stateList = mergeSet.ToList(); var outputState = stateList[0]; // If this statelist contains the startstate, the new startstate will have to be // the new output state if (stateList.Contains(StartState)) { StartState = outputState; } // Iterate over all the states in the merge list except for the one we have decided // to merge everything into. for (int i = 1; i < stateList.Count; ++i) { var toRemove = stateList[i]; // Find all transitions that went to this state var toTransitions = Transitions.Where(f => f.To == toRemove).ToList(); foreach (var transition in toTransitions) { // There can be two cases here, either there already is a new transition to be found, in // which case we can merge the valid input instead. The alternative is that there is no prior // transition, in which case we repoint our transition to the output state. var existingTransition = Transitions.FirstOrDefault(f => f.From == transition.From && f.To == outputState); if (existingTransition != null) { existingTransition.ValidInput.UnionWith(transition.ValidInput); Transitions.Remove(transition); // Remove the old transition } else { transition.To = outputState; } } // Find all transitions that went from this state var fromTransitions = Transitions.Where(f => f.From == toRemove).ToList(); foreach (var transition in fromTransitions) { // Same two cases as the code above var existingTransition = Transitions.FirstOrDefault(f => f.From == outputState && f.To == transition.To); if (existingTransition != null) { existingTransition.ValidInput.UnionWith(transition.ValidInput); Transitions.Remove(transition); // Remove the old transition } else { transition.From = outputState; } } // Since before removing this state, we need to merge the list of NFA states that created both of these states foreach (var nfaState in toRemove.NfaStates) { if (!outputState.NfaStates.Contains(nfaState)) { outputState.NfaStates.Add(nfaState); } } // There should be no more references to this state. It can thus be removed. States.Remove(toRemove); } } // The states now need to be renumbered AssignStateNumbers(); } public override IEnumerable<State> Closure(State[] states, ISet<State> visitedStates = null) { return states; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; namespace Sugar.Command.Binder { /// <summary> /// Class to represent the applications command line parameters. /// </summary> public class Parameters : List<string>, ICloneable { public static IEnumerable<string> DefaultSwitches => new List<string> {"-", "--", "/"}; /// <summary> /// Initializes a new instance of the <see cref="Parameters"/> class with /// the <see cref="Environment.CommandLine" /> input and <see cref="DefaultSwitches"/>. /// </summary> public Parameters() : this(Environment.CommandLine, DefaultSwitches) { } /// <summary> /// Initializes a new instance of the <see cref="Parameters"/> class with /// the specified <see cref="args"/> and <see cref="DefaultSwitches"/>. /// </summary> /// <param name="args">The args.</param> public Parameters(string args) : this(args, DefaultSwitches) { } /// <summary> /// Initializes a new instance of the <see cref="Parameters"/> class with /// the specified <see cref="args"/> and <see cref="switches"/>. /// </summary> /// <param name="args">The args.</param> /// <param name="switches">The switches.</param> public Parameters(string args, IEnumerable<string> switches) { Switches = switches; if (string.IsNullOrWhiteSpace(args)) return; var parsed = args.ParseCommandLine(); // The first parameter is the program's name // Set current filename and remove it Filename = parsed[0]; parsed.RemoveAt(0); AddRange(parsed); } /// <summary> /// Copy constructor. /// </summary> /// <param name="original">The instance to be copied.</param> public Parameters(Parameters original) { var switches = new List<string>(); switches.AddRange(original.Switches); Switches = switches; Filename = original.Filename; AddRange(original); } /// <summary> /// Gets the current filename of the executable. /// </summary> public string Filename { get; } private static string directory; /// <summary> /// Gets the current directory of the executing assembly. /// </summary> public static string Directory { get { if (string.IsNullOrEmpty(directory)) { var codebase = Assembly.GetExecutingAssembly().GetName().CodeBase; // Get assembly directory if (!string.IsNullOrEmpty(codebase)) { directory = Path.GetDirectoryName(codebase) ?? string.Empty; } else { directory = System.IO.Directory.GetCurrentDirectory(); } directory = directory.Replace("file:\\", ""); } return directory; } } /// <summary> /// Gets or sets the command switches. /// </summary> /// <value> /// By default, values starting with "-", "--" or "/" /// </value> public IEnumerable<string> Switches { get; } /// <summary> /// Returns a parameter as a string value /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public string AsString(string name) { return AsString(name, string.Empty); } /// <summary> /// Returns a parameter as a string value /// </summary> /// <param name="name">The name.</param> /// <param name="default">The @default value.</param> /// <returns></returns> public string AsString(string name, string @default) { return AsStrings(name, @default).First(); } /// <summary> /// Returns a parameter as a string value /// </summary> /// <param name="name">The name.</param> /// <param name="defaults">The default values.</param> /// <returns></returns> public IList<string> AsStrings(string name, params string[] defaults) { var result = new List<string>(); var index = IndexOf(name); while (index > -1 && Count > index + 1) { if (IsFlag(this[index + 1]) && Switches.Any()) { break; } result.Add(this[index + 1]); index++; } if (result.Count == 0) result.AddRange(defaults); return result; } /// <summary> /// Returns a parameter as an integer value /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public int AsInteger(string name) { return AsInteger(name, 0); } /// <summary> /// Returns a parameter as an integer value /// </summary> /// <param name="name">The name.</param> /// <param name="default">The @default value.</param> /// <returns></returns> public int AsInteger(string name, int @default) { var resultAsString = AsString(name); if (!int.TryParse(resultAsString, out var result)) { result = @default; } return result; } /// <summary> /// Returns a parameter as an integer value /// </summary> /// <param name="name">The name.</param> /// <returns> /// Today if not found /// </returns> public DateTime AsDateTime(string name) { return AsDateTime(name, DateTime.Today); } /// <summary> /// Returns a parameter as an integer value /// </summary> /// <param name="name">The name.</param> /// <param name="default">The @default value.</param> /// <returns></returns> public DateTime AsDateTime(string name, DateTime @default) { var resultAsString = AsString(name); if (!DateTime.TryParse(resultAsString, out var result)) { result = @default; } return result; } /// <summary> /// Determines whether the specified name contains argument. /// </summary> /// <param name="names">The names.</param> /// <returns> /// <c>true</c> if the specified name contains argument; otherwise, <c>false</c>. /// </returns> public new bool Contains(string names) { return IndexOf(names) > -1; } public bool ContainsAny(params string[] names) { return ContainsAny(names as IEnumerable<string>); } /// <summary> /// Determines whether the specified name contains argument. /// </summary> /// <param name="names">The names.</param> /// <returns> /// <c>true</c> if the specified name contains argument; otherwise, <c>false</c>. /// </returns> public bool ContainsAny(IEnumerable<string> names) { return names.All(name => IndexOf(name) != -1); } /// <summary> /// Gets the index of the parameter with the given name /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public new int IndexOf(string name) { var result = -1; var switches = new List<string>(Switches); if (switches.Count == 0) switches.Add(string.Empty); foreach (var @switch in switches) { result = base.IndexOf(string.Concat(@switch, name)); if (result > -1) break; } return result; } /// <summary> /// Gets the boolean value /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public bool AsBool(string name) { return AsBool(name, false); } /// <summary> /// Gets the boolean value /// </summary> /// <param name="name">The name.</param> /// <param name="default">if set to <c>true</c> [@default].</param> /// <returns></returns> public bool AsBool(string name, bool @default) { var resultAsString = AsString(name, @default.ToString()); if (!bool.TryParse(resultAsString, out var result)) { result = @default; } return result; } public override string ToString() { var sb = new StringBuilder(); foreach (var parameter in this) { if (sb.Length > 0) sb.Append(" "); if (parameter.Contains(" ")) { sb.Append(@""""); } sb.Append(parameter); if (parameter.Contains(" ")) { sb.Append(@""""); } } return sb.ToString(); } /// <summary> /// Clones this instance into a new copy. /// </summary> /// <returns></returns> public object Clone() { return new Parameters(this); } /// <summary> /// Removes the specified name. /// </summary> /// <param name="name">The name.</param> public new void Remove(string name) { var index = IndexOf(name); if (index <= -1) return; var length = AsStrings(name).Count + 1; RemoveRange(index, length); } /// <summary> /// Replaces the value of the parameter with the specified key. /// </summary> /// <param name="name">The name.</param> /// <param name="values">The values.</param> public void Replace(string name, params string[] values) { var index = IndexOf(name); if (index <= -1) return; if (Switches.Any()) { var length = AsStrings(name).Count; if (index + 1 + length <= Count) RemoveRange(index + 1, length); InsertRange(index + 1, values); } else { RemoveAt(index); InsertRange(index, values); } } /// <summary> /// Determines whether the specified name is a command flag. /// </summary> /// <param name="name">The name.</param> /// <returns> /// <c>true</c> if the specified name is flag; otherwise, <c>false</c>. /// </returns> public bool IsFlag(string name) { return !Switches.Any() || Switches.Any(name.StartsWith); } public T AsCustomType<T>(string name) { return (T) AsCustomType(name, typeof(T)); } public object AsCustomType(string name, Type type) { object result = null; if (Contains(name)) { var value = AsString(name); if (Nullable.GetUnderlyingType(type) != null) { if (DateTime.TryParse(value, out var date)) { result = date; } } else { result = Convert.ChangeType(value, type); } } return result; } public object AsCustomType(int index, Type type) { object result = null; if (index < Count) { result = Convert.ChangeType(this[index], type); } return result; } /// <summary> /// Determines whether the specified name has a value. /// </summary> /// <param name="name">The name.</param> /// <returns> /// <c>true</c> if the specified name has value; otherwise, <c>false</c>. /// </returns> public bool HasValue(string name) { return AsStrings(name).Count > 0; } } }
// // IWidgetBackend.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Drawing; namespace Xwt.Backends { /// <summary> /// The Xwt widget backend base interface. All Xwt widget backends implement it. /// </summary> public interface IWidgetBackend: IBackend { /// <summary> /// Initialize the backend with the specified EventSink. /// </summary> /// <param name="eventSink">The frontend event sink (usually the <see cref="Xwt.Backends.BackendHost"/> of the frontend).</param> void Initialize (IWidgetEventSink eventSink); /// <summary> /// Releases all resources used by the widget /// </summary> /// <remarks> /// This method is called to free all managed and unmanaged resources held by the backend. /// In general, the backend should destroy the native widget at this point. /// When a widget that has children is disposed, the Dispose method is called on all /// backends of all widgets in the children hierarchy. /// </remarks> void Dispose (); /// <summary> /// Gets or sets a value indicating whether this widget is visible. /// </summary> /// <value><c>true</c> if visible; otherwise, <c>false</c>.</value> bool Visible { get; set; } /// <summary> /// Gets or sets a value indicating whether this widget is sensitive/enabled. /// </summary> /// <value><c>true</c> if sensitive; otherwise, <c>false</c>.</value> bool Sensitive { get; set; } /// <summary> /// Gets or sets the name of this widget. /// </summary> string Name { get; set; } /// <summary> /// Gets or sets a value indicating whether this widget can get focus. /// </summary> /// <value><c>true</c> if this instance can get focus; otherwise, <c>false</c>.</value> bool CanGetFocus { get; set; } /// <summary> /// Gets a value indicating whether this widget has the focus. /// </summary> /// <value><c>true</c> if this widget has the focus; otherwise, <c>false</c>.</value> bool HasFocus { get; } /// <summary> /// Gets or sets the opacity of this widget. /// </summary> /// <value>The opacity.</value> double Opacity { get; set; } /// <summary> /// Gets the final size of this widget. /// </summary> /// <value>The size.</value> Size Size { get; } /// <summary> /// Converts widget relative coordinates to its parents coordinates. /// </summary> /// <returns>The parent coordinates.</returns> /// <param name="widgetCoordinates">The relative widget coordinates.</param> Point ConvertToParentCoordinates (Point widgetCoordinates); /// <summary> /// Converts widget relative coordinates to its parent window coordinates. /// </summary> /// <returns>The window coordinates.</returns> /// <param name="widgetCoordinates">The relative widget coordinates.</param> Point ConvertToWindowCoordinates (Point widgetCoordinates); /// <summary> /// Converts widget relative coordinates to screen coordinates. /// </summary> /// <returns>The screen coordinates.</returns> /// <param name="widgetCoordinates">The relative widget coordinates.</param> Point ConvertToScreenCoordinates (Point widgetCoordinates); /// <summary> /// Sets the minimum size of the widget /// </summary> /// <param name='width'> /// Minimum width. If the value is -1, it means no minimum width. /// </param> /// <param name='height'> /// Minimum height. If the value is -1, it means no minimum height. /// </param> void SetMinSize (double width, double height); /// <summary> /// Sets the size request / natural size of this widget. /// </summary> /// <param name="width">Natural width, or -1 if no custom natural width has been set.</param> /// <param name="height">Natural height, or -1 if no custom natural height has been set.</param> void SetSizeRequest (double width, double height); /// <summary> /// Sets the focus on this widget. /// </summary> void SetFocus (); /// <summary> /// Updates the layout of this widget. /// </summary> void UpdateLayout (); /// <summary> /// Gets the preferred size of this widget. /// </summary> /// <returns>The widgets preferred size.</returns> /// <param name="widthConstraint">Width constraint.</param> /// <param name="heightConstraint">Height constraint.</param> Size GetPreferredSize (SizeConstraint widthConstraint, SizeConstraint heightConstraint); /// <summary> /// Gets the native toolkit widget. /// </summary> /// <value>The native widget.</value> object NativeWidget { get; } /// <summary> /// Starts a drag operation originated in this widget /// </summary> /// <param name='data'> /// Drag operation arguments /// </param> void DragStart (DragStartData data); /// <summary> /// Sets up a widget so that XWT will start a drag operation when the user clicks and drags on the widget. /// </summary> /// <param name='types'> /// Types of data that can be dragged from this widget /// </param> /// <param name='dragAction'> /// Bitmask of possible actions for a drag from this widget /// </param> /// <remarks> /// When a drag operation is started, the backend should fire the OnDragStarted event /// </remarks> void SetDragSource (TransferDataType[] types, DragDropAction dragAction); /// <summary> /// Sets a widget as a potential drop destination /// </summary> /// <param name='types'> /// Types of data that can be dropped on this widget /// </param> /// <param name='dragAction'> /// Bitmask of possible actions for a drop on this widget /// </param> void SetDragTarget (TransferDataType[] types, DragDropAction dragAction); void UnregisterDragTarget(); /// <summary> /// Gets or sets the native font of this widget. /// </summary> /// <value>The font.</value> object Font { get; set; } /// <summary> /// Gets or sets the background color of this widget. /// </summary> /// <value>The background color.</value> Color BackgroundColor { get; set; } /// <summary> /// Gets or sets the text color of this widget. /// </summary> /// <value>The text color.</value> Color TextColor { get; set; } /// <summary> /// Gets or sets the tooltip text. /// </summary> /// <value>The tooltip text.</value> string TooltipText { get; set; } /// <summary> /// Sets the cursor shape to be used when the mouse is over the widget /// </summary> /// <param name='cursorType'> /// The cursor type. /// </param> void SetCursor (CursorType cursorType); } /// <summary> /// The widget event sink routes backend events to the frontend /// </summary> public interface IWidgetEventSink { /// <summary> /// Notifies the frontend that the mouse is moved over the widget in a drag operation, /// to check whether a drop operation is allowed. /// </summary> /// <param name="args">The drag over check event arguments.</param> /// <remarks> /// This event handler provides information about the type of the data that is going /// to be dropped, but not the actual data. /// The frontend decides which of the proposed actions will be performed when /// the item is dropped by setting <see cref="Xwt.DragOverCheckEventArgs.AllowedAction"/>. /// If the value is not set or it is set to <see cref="Xwt.DragDropAction.Default"/>, /// the action data should be provided using <see cref="OnDragOver"/>. If the proposed action /// is not allowed, the backend should not allow the user to perform the drop action. /// </remarks> void OnDragOverCheck (DragOverCheckEventArgs args); /// <summary> /// Notifies the frontend that the mouse is moved over the widget in a drag operation, /// to check whether a drop operation is allowed for the data being dragged. /// </summary> /// <param name="args">The drag over event arguments.</param> /// <remarks> /// This event handler provides information about the actual data that is going to be dropped. /// The frontend decides which of the proposed actions will be performed when the /// item is dropped by setting <see cref="Xwt.DragOverEventArgs.AllowedAction"/>. If the proposed action /// is not allowed, the backend should not perform the drop action. /// </remarks> void OnDragOver (DragOverEventArgs args); /// <summary> /// Notifies the frontend that there is a pending drop operation, to check whether it is allowed. /// </summary> /// <param name="args">The drop check event arguments.</param> /// <remarks> /// This event handler provides information about the type of the data that is going /// to be dropped, but not the actual data. The frontend decides whether the action /// is allowed or not by setting <see cref="Xwt.DragCheckEventArgs.Result"/>. /// The backend should abort the drop operation, if the result is <see cref="Xwt.DragDropResult.Canceled"/>, /// or provide more information including actual data using <see cref="OnDragDrop"/> otherwise. /// </remarks> void OnDragDropCheck (DragCheckEventArgs args); /// <summary> /// Notifies the frontend of a drop operation to perform. /// </summary> /// <param name="args">The drop event arguments.</param> /// <remarks> /// This event handler provides information about the dropped data and the actual data. /// The frontend will set <see cref="Xwt.DragEventArgs.Success"/> to <c>true</c> when the drop /// was successful, <c>false</c> otherwise. /// </remarks> void OnDragDrop (DragEventArgs args); /// <summary> /// Notifies the frontend that the mouse is leaving the widget in a drag operation. /// </summary> void OnDragLeave (EventArgs args); /// <summary> /// Notifies the frontend that the drag&amp;drop operation has finished. /// </summary> /// <param name="args">The event arguments.</param> void OnDragFinished (DragFinishedEventArgs args); /// <summary> /// Notifies the frontend about a starting drag operation and retrieves the data for the drag&amp;drop operation. /// </summary> /// <returns> /// The information about the starting drag operation and the data to be transferred, /// or <c>null</c> to abort dragging. /// </returns> DragStartData OnDragStarted (); /// <summary> /// Notifies the frontend that a key has been pressed. /// </summary> /// <param name="args">The Key arguments.</param> void OnKeyPressed (KeyEventArgs args); /// <summary> /// Notifies the frontend that a key has been released. /// </summary> /// <param name="args">The Key arguments.</param> void OnKeyReleased (KeyEventArgs args); /// <summary> /// Notifies the frontend that a text has been entered. /// </summary> /// <param name="args">The text input arguments.</param> void OnTextInput (TextInputEventArgs args); /// <summary> /// Notifies the frontend that the widget has received the focus. /// </summary> void OnGotFocus (); /// <summary> /// Notifies the frontend that the widget has lost the focus. /// </summary> void OnLostFocus (); /// <summary> /// Notifies the frontend that the mouse has entered the widget. /// </summary> void OnMouseEntered (); /// <summary> /// Notifies the frontend that the mouse has left the widget. /// </summary> void OnMouseExited (); /// <summary> /// Notifies the frontend that a mouse button has been pressed. /// </summary> /// <param name="args">The button arguments.</param> void OnButtonPressed (ButtonEventArgs args); /// <summary> /// Notifies the frontend that a mouse button has been released. /// </summary> /// <param name="args">The button arguments.</param> void OnButtonReleased (ButtonEventArgs args); /// <summary> /// Notifies the frontend that the mouse has moved. /// </summary> /// <param name="args">The mouse movement arguments.</param> void OnMouseMoved (MouseMovedEventArgs args); /// <summary> /// Notifies the frontend that the widget bounds have changed. /// </summary> void OnBoundsChanged (); /// <summary> /// Notifies the frontend about a scroll action. /// </summary> /// <param name="args">The mouse scrolled arguments.</param> void OnMouseScrolled(MouseScrolledEventArgs args); /// <summary> /// Gets the preferred size from the frontend (it will not include the widget margin). /// </summary> /// <returns>The size preferred by the frontend without widget margin.</returns> /// <param name="widthConstraint">The width constraint.</param> /// <param name="heightConstraint">The height constraint.</param> /// <remarks> /// The returned size is >= 0. If a constraint is specified, the returned size will not /// be bigger than the constraint. In most cases the frontend will retrieve the preferred size /// from the backend using <see cref="Xwt.Backends.IWidgetBackend.GetPreferredSize"/> and adjust it /// optionally. /// </remarks> Size GetPreferredSize (SizeConstraint widthConstraint = default(SizeConstraint), SizeConstraint heightConstraint = default(SizeConstraint)); /// <summary> /// Notifies the frontend that the preferred size of this widget has changed /// </summary> /// <remarks> /// This method must be called when the widget changes its preferred size. /// This method doesn't need to be called if the resize is the result of changing /// a widget property. For example, it is not necessary to call it when the text /// of a label is changed (the fronted will automatically rise this event when /// the property changes). However, it has to be called when the the shape of the /// widget changes on its own, for example if the size of a button changes as /// a result of clicking on it. /// </remarks> void OnPreferredSizeChanged (); /// <summary> /// Gets a value indicating whether the frontend supports custom scrolling. /// </summary> /// <returns><c>true</c>, if custom scrolling is supported, <c>false</c> otherwise.</returns> /// <remarks> /// If the frontend supports custom scrolling, the backend must set the scroll adjustments /// using <see cref="SetScrollAdjustments"/> to allow the frontend to handle scrolling. /// </remarks> bool SupportsCustomScrolling (); /// <summary> /// Sets the scroll adjustments for custom scrolling. /// </summary> /// <param name="horizontal">The horizontal adjustment backend.</param> /// <param name="vertical">The vertical adjustment backend.</param> void SetScrollAdjustments (IScrollAdjustmentBackend horizontal, IScrollAdjustmentBackend vertical); /// <summary> /// Gets the default natural size of the widget /// </summary> /// <returns> /// The default natural size. /// </returns> /// <remarks> /// This method should only be used if there isn't a platform-specific natural /// size for the widget. There may be widgets for which XWT can't provide /// a default natural width or height, in which case it return 0. /// </remarks> Size GetDefaultNaturalSize (); } /// <summary> /// Event identifiers supported by all Xwt widgets to subscribe to /// </summary> [Flags] public enum WidgetEvent { /// <summary> The widget can/wants to validate the type of a drag over operation. </summary> DragOverCheck = 1, /// <summary> The widget can/wants to validate the data of a drag over operation. </summary> DragOver = 1 << 1, /// <summary> The widget can/wants to validate a drop operation by its type. </summary> DragDropCheck = 1 << 2, /// <summary> The widget can/wants to validate the data of and perform a drop operation. </summary> DragDrop = 1 << 3, /// <summary> The widget can/wants to be notified of leaving drag operations. </summary> DragLeave = 1 << 4, /// <summary> The widget can/wants to be notified of pressed keys. </summary> KeyPressed = 1 << 5, /// <summary> The widget can/wants to be notified of released keys. </summary> KeyReleased = 1 << 6, /// <summary> The widget wants to check its size when it changes. </summary> PreferredSizeCheck = 1 << 7, /// <summary> The widget can/wants to be notified when it receives the focus. </summary> GotFocus = 1 << 8, /// <summary> The widget can/wants to be notified when it looses the focus. </summary> LostFocus = 1 << 9, /// <summary> The widget can/wants to be notified when the mouse enters it. </summary> MouseEntered = 1 << 10, /// <summary> The widget can/wants to be notified when the mouse leaves it. </summary> MouseExited = 1 << 11, /// <summary> The widget can/wants to be notified of pressed buttons. </summary> ButtonPressed = 1 << 12, /// <summary> The widget can/wants to be notified of released buttons. </summary> ButtonReleased = 1 << 13, /// <summary> The widget can/wants to be notified of mouse movements. </summary> MouseMoved = 1 << 14, /// <summary> The widget can/wants to be notified when a drag operation starts. </summary> DragStarted = 1 << 15, /// <summary> The widget can/wants to be notified when its bounds change. </summary> BoundsChanged = 1 << 16, /// <summary> The widget can/wants to be notified of scroll events. </summary> MouseScrolled = 1 << 17, /// <summary> The widget can/wants to be notified of text input events. </summary> TextInput = 1 << 18 } /// <summary> /// Arguments for a starting drag&amp;drop operation. /// </summary> public class DragStartData { /// <summary> /// Gets the collection of data to be transferred through the drag operation. /// </summary> /// <value>The data to transfer.</value> public TransferDataSource Data { get; private set; } /// <summary> /// Gets the type of the drag action. /// </summary> /// <value>The drag action type.</value> public DragDropAction DragAction { get; private set; } /// <summary> /// Gets the image backend of the drag image. /// </summary> /// <value>The drag icon backend.</value> public object ImageBackend { get; private set; } /// <summary> /// Gets X coordinate of the drag image hotspot. /// </summary> /// <value>The image hotspot X coordinate.</value> public double HotX { get; private set; } /// <summary> /// Gets Y coordinate of the drag image hotspot. /// </summary> /// <value>The image hotspot Y coordinate.</value> public double HotY { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Xwt.Backends.DragStartData"/> class. /// </summary> /// <param name="data">The collection of data to be transferred through drag operation.</param> /// <param name="action">The type of the drag action.</param> /// <param name="imageBackend">The image backend of the drag image.</param> /// <param name="hotX">The image hotspot X coordinate.</param> /// <param name="hotY">The image hotspot Y coordinate.</param> internal DragStartData (TransferDataSource data, DragDropAction action, object imageBackend, double hotX, double hotY) { Data = data; DragAction = action; ImageBackend = imageBackend; HotX = hotX; HotY = hotY; } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace Palaso.UI.WindowsForms.Widgets.BetterGrid { #region SilButtonCell class /// ---------------------------------------------------------------------------------------- /// <summary> /// Extends the DataGridViewTextBoxCell to include a button on the right side of the cell. /// Sort of like a combo box cell, only the button can be used to drop-down a custom /// control. /// </summary> /// ---------------------------------------------------------------------------------------- public class PushButtonCell : DataGridViewTextBoxCell { private bool _mouseOverButton; private bool _mouseDownOnButton; private bool _enabled = true; /// ------------------------------------------------------------------------------------ /// <summary> /// Repaint the cell when it's enabled property changes. /// </summary> /// ------------------------------------------------------------------------------------ public bool Enabled { get { return _enabled; } set { _enabled = value; DataGridView.InvalidateCell(this); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the cell's owning SilButtonColumn. /// </summary> /// ------------------------------------------------------------------------------------ public PushButtonColumn OwningButtonColumn { get { if (DataGridView == null || ColumnIndex < 0 || ColumnIndex >= DataGridView.Columns.Count) { return null; } return (DataGridView.Columns[ColumnIndex] as PushButtonColumn); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets a value indicating whether or not the cell's button should be shown. /// </summary> /// ------------------------------------------------------------------------------------ public bool ShowButton { get { bool owningColShowValue = (OwningButtonColumn != null && OwningButtonColumn.ShowButton); var row = DataGridView.CurrentRow; return (owningColShowValue && RowIndex >= 0 && ((row == null && DataGridView.AllowUserToAddRows) || (row != null && RowIndex == row.Index))); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets a value indicating whether or not the specified point is over the cell's /// radio button. The relativeToCell flag is true when the specified point's origin /// is relative to the upper right corner of the cell. When false, it's assumed the /// point's origin is relative to the cell's owning grid control. /// </summary> /// ------------------------------------------------------------------------------------ public bool IsPointOverButton(Point pt, bool relativeToCell) { // Get the rectangle for the radion button area. Rectangle rc = DataGridView.GetCellDisplayRectangle(ColumnIndex, RowIndex, false); Rectangle rcrb; Rectangle rcText; GetRectangles(rc, out rcrb, out rcText); if (relativeToCell) { // Set the button's rectangle location // relative to the cell instead of the grid. rcrb.X -= rc.X; rcrb.Y -= rc.Y; } return rcrb.Contains(pt); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnMouseLeave(int rowIndex) { base.OnMouseLeave(rowIndex); _mouseOverButton = false; DataGridView.InvalidateCell(this); ManageButtonToolTip(); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { base.OnMouseMove(e); if (!_enabled) return; if (!IsPointOverButton(e.Location, true) && _mouseOverButton) { _mouseOverButton = false; DataGridView.InvalidateCell(this); ManageButtonToolTip(); } else if (IsPointOverButton(e.Location, true) && !_mouseOverButton) { _mouseOverButton = true; DataGridView.InvalidateCell(this); ManageButtonToolTip(); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Monitor when the mouse button goes down over the button. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { base.OnMouseDown(e); if (_mouseOverButton && !_mouseDownOnButton) { _mouseDownOnButton = true; DataGridView.InvalidateCell(this); ManageButtonToolTip(); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Monitor when the user releases the mouse button. /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { _mouseDownOnButton = false; base.OnMouseUp(e); DataGridView.InvalidateCell(this); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) { if (!IsPointOverButton(e.Location, true) || !ShowButton || IsInEditMode) { base.OnMouseClick(e); return; } PushButtonColumn col = DataGridView.Columns[ColumnIndex] as PushButtonColumn; if (col != null) col.InvokeButtonClick(e); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ private void ManageButtonToolTip() { if (OwningButtonColumn != null && _mouseOverButton && !_mouseDownOnButton) OwningButtonColumn.ShowToolTip(); else OwningButtonColumn.HideToolTip(); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected override void Paint(Graphics g, Rectangle clipBounds, Rectangle bounds, int rowIndex, DataGridViewElementStates state, object value, object formattedValue, string errorText, DataGridViewCellStyle style, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts parts) { bool useEllipsisPath = (OwningButtonColumn != null && OwningButtonColumn.DrawTextWithEllipsisPath); if (!ShowButton && !useEllipsisPath) { base.Paint(g, clipBounds, bounds, rowIndex, state, value, formattedValue, errorText, style, advancedBorderStyle, parts); return; } // Draw default everything but text. parts &= ~DataGridViewPaintParts.ContentForeground; base.Paint(g, clipBounds, bounds, rowIndex, state, value, formattedValue, errorText, style, advancedBorderStyle, parts); // Get the rectangles for the two parts of the cell. Rectangle rcbtn; Rectangle rcText; GetRectangles(bounds, out rcbtn, out rcText); DrawButton(g, rcbtn); DrawCellText(g, value as string, style, rcText); } /// ------------------------------------------------------------------------------------ /// <summary> /// Draws the button in the cell. /// </summary> /// ------------------------------------------------------------------------------------ private void DrawButton(Graphics g, Rectangle rcbtn) { if (!ShowButton) return; var buttonStyle = OwningButtonColumn.ButtonStyle; if (buttonStyle == PushButtonColumn.ButtonType.MinimalistCombo) DrawMinimalistButton(g, rcbtn); else { if ((buttonStyle == PushButtonColumn.ButtonType.VisualStyleCombo || buttonStyle == PushButtonColumn.ButtonType.VisualStylePush) && !DrawVisualStyledButton(buttonStyle, g, rcbtn)) { DrawPlainButton(buttonStyle, g, rcbtn); } } string buttonText = (OwningButtonColumn == null ? null : OwningButtonColumn.ButtonText); if (string.IsNullOrEmpty(buttonText)) return; var buttonFont = (OwningButtonColumn == null ? SystemInformation.MenuFont : OwningButtonColumn.ButtonFont); // Draw text const TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix | TextFormatFlags.EndEllipsis | TextFormatFlags.NoPadding | TextFormatFlags.PreserveGraphicsClipping; Color clrText = (_enabled ? SystemColors.ControlText : SystemColors.GrayText); TextRenderer.DrawText(g, buttonText, buttonFont, rcbtn, clrText, flags); } /// ------------------------------------------------------------------------------------ private void DrawMinimalistButton(Graphics g, Rectangle rc) { var element = GetVisualStyleComboButton(); rc = AdjustRectToDefaultComboButtonWidth(rc); if (element != VisualStyleElement.ComboBox.DropDownButton.Normal && element != VisualStyleElement.ComboBox.DropDownButton.Disabled && BetterGrid.CanPaintVisualStyle(element)) { var renderer = new VisualStyleRenderer(element); renderer.DrawBackground(g, rc); } else { var pen = (element == VisualStyleElement.ComboBox.DropDownButton.Disabled ? SystemPens.GrayText : SystemPens.WindowText); var x = rc.X + (int)Math.Round((rc.Width - 7) / 2f, MidpointRounding.AwayFromZero); var y = rc.Y + (int)Math.Round((rc.Height - 4) / 2f, MidpointRounding.AwayFromZero); g.DrawLine(pen, x, y, x + 6, y++); g.DrawLine(pen, x + 1, y, x + 5, y++); g.DrawLine(pen, x + 2, y, x + 4, y); g.DrawLine(pen, x + 3, y, x + 3, y + 1); return; } } /// ------------------------------------------------------------------------------------ private bool DrawVisualStyledButton(PushButtonColumn.ButtonType buttonStyle, IDeviceContext g, Rectangle rcbtn) { VisualStyleElement element = (buttonStyle == PushButtonColumn.ButtonType.VisualStyleCombo ? GetVisualStyleComboButton() : GetVisualStylePushButton()); if (!BetterGrid.CanPaintVisualStyle(element)) return false; VisualStyleRenderer renderer = new VisualStyleRenderer(element); rcbtn = AdjustRectToDefaultComboButtonWidth(rcbtn); renderer.DrawBackground(g, rcbtn); return true; } /// ------------------------------------------------------------------------------------ private Rectangle AdjustRectToDefaultComboButtonWidth(Rectangle rc) { if (!OwningButtonColumn.DrawDefaultComboButtonWidth) return rc; var rcNew = rc; rcNew.Width = SystemInformation.VerticalScrollBarWidth; rcNew.X = (rc.Right - rcNew.Width); return rcNew; } /// ------------------------------------------------------------------------------------ private void DrawPlainButton(PushButtonColumn.ButtonType type, Graphics g, Rectangle rcbtn) { ButtonState state = (_mouseDownOnButton && _mouseOverButton && _enabled ? ButtonState.Pushed : ButtonState.Normal); if (!_enabled) state |= ButtonState.Inactive; if (type != PushButtonColumn.ButtonType.PlainCombo) ControlPaint.DrawButton(g, rcbtn, state); else { rcbtn = AdjustRectToDefaultComboButtonWidth(rcbtn); ControlPaint.DrawComboButton(g, rcbtn, state); } } /// ------------------------------------------------------------------------------------ /// <summary> /// Draws the cell's text. /// </summary> /// ------------------------------------------------------------------------------------ private void DrawCellText(IDeviceContext g, string text, DataGridViewCellStyle style, Rectangle rcText) { if (string.IsNullOrEmpty(text)) return; // Determine the text's proper foreground color. Color clrText = SystemColors.GrayText; if (_enabled && DataGridView != null) clrText = (Selected ? style.SelectionForeColor : style.ForeColor); bool useEllipsisPath = (OwningButtonColumn != null && OwningButtonColumn.DrawTextWithEllipsisPath); TextFormatFlags flags = TextFormatFlags.LeftAndRightPadding | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix | (useEllipsisPath ? TextFormatFlags.PathEllipsis : TextFormatFlags.EndEllipsis) | TextFormatFlags.PreserveGraphicsClipping; TextRenderer.DrawText(g, text, style.Font, rcText, clrText, flags); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the correct visual style push button given the state of the cell. /// </summary> /// ------------------------------------------------------------------------------------ private VisualStyleElement GetVisualStylePushButton() { VisualStyleElement element = VisualStyleElement.Button.PushButton.Normal; if (!_enabled) element = VisualStyleElement.Button.PushButton.Disabled; else if (_mouseOverButton) { element = (_mouseDownOnButton ? VisualStyleElement.Button.PushButton.Pressed : VisualStyleElement.Button.PushButton.Hot); } return element; } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the correct visual style combo button given the state of the cell. /// </summary> /// ------------------------------------------------------------------------------------ private VisualStyleElement GetVisualStyleComboButton() { VisualStyleElement element = VisualStyleElement.ComboBox.DropDownButton.Normal; if (!_enabled) element = VisualStyleElement.ComboBox.DropDownButton.Disabled; else if (_mouseOverButton) { element = (_mouseDownOnButton ? VisualStyleElement.ComboBox.DropDownButton.Pressed : VisualStyleElement.ComboBox.DropDownButton.Hot); } return element; } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the rectangle for the radio button and the text, given the specified cell /// bounds. /// </summary> /// <param name="bounds">The rectangle of the entire cell.</param> /// <param name="rcbtn">The returned rectangle for the button.</param> /// <param name="rcText">The returned rectangle for the text.</param> /// ------------------------------------------------------------------------------------ public void GetRectangles(Rectangle bounds, out Rectangle rcbtn, out Rectangle rcText) { if (!ShowButton) { rcbtn = Rectangle.Empty; rcText = bounds; return; } int buttonWidth = (OwningButtonColumn == null ? SystemInformation.VerticalScrollBarWidth : OwningButtonColumn.ButtonWidth); bool paintComboButton = (OwningButtonColumn == null ? false : OwningButtonColumn.ButtonStyle != PushButtonColumn.ButtonType.PlainPush && OwningButtonColumn.ButtonStyle != PushButtonColumn.ButtonType.VisualStylePush); if (paintComboButton) buttonWidth += 2; rcText = bounds; rcText.Width -= buttonWidth; rcbtn = bounds; rcbtn.Width = buttonWidth; rcbtn.X = bounds.Right - buttonWidth - 1; rcbtn.Y--; if (paintComboButton) { rcbtn.Width -= 2; rcbtn.Height -= 3; rcbtn.X++; rcbtn.Y += 2; } } } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection.Internal; using System.Runtime.CompilerServices; using System.Text; namespace System.Reflection.Metadata.Ecma335 { public sealed partial class MetadataBuilder { private sealed class HeapBlobBuilder : BlobBuilder { private int _capacityExpansion; public HeapBlobBuilder(int capacity) : base(capacity) { } protected override BlobBuilder AllocateChunk(int minimalSize) { return new HeapBlobBuilder(Math.Max(Math.Max(minimalSize, ChunkCapacity), _capacityExpansion)); } internal void SetCapacity(int capacity) { _capacityExpansion = Math.Max(0, capacity - Count - FreeBytes); } } // #US heap private const int UserStringHeapSizeLimit = 0x01000000; private readonly Dictionary<string, UserStringHandle> _userStrings = new Dictionary<string, UserStringHandle>(256); private readonly HeapBlobBuilder _userStringBuilder = new HeapBlobBuilder(4 * 1024); private readonly int _userStringHeapStartOffset; // #String heap private Dictionary<string, StringHandle> _strings = new Dictionary<string, StringHandle>(256); private readonly HeapBlobBuilder _stringBuilder = new HeapBlobBuilder(4 * 1024); private readonly int _stringHeapStartOffset; // map allocated when the String heap is serialized: private int[] _stringVirtualIndexToHeapOffsetMap; private bool HeapsCompleted => _stringVirtualIndexToHeapOffsetMap != null; // #Blob heap private readonly Dictionary<ImmutableArray<byte>, BlobHandle> _blobs = new Dictionary<ImmutableArray<byte>, BlobHandle>(1024, ByteSequenceComparer.Instance); private readonly int _blobHeapStartOffset; private int _blobHeapSize; // #GUID heap private readonly Dictionary<Guid, GuidHandle> _guids = new Dictionary<Guid, GuidHandle>(); private readonly HeapBlobBuilder _guidBuilder = new HeapBlobBuilder(16); // full metadata has just a single guid /// <summary> /// Creates a builder for metadata tables and heaps. /// </summary> /// <param name="userStringHeapStartOffset"> /// Start offset of the User String heap. /// The cumulative size of User String heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata. /// </param> /// <param name="stringHeapStartOffset"> /// Start offset of the String heap. /// The cumulative size of String heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata. /// </param> /// <param name="blobHeapStartOffset"> /// Start offset of the Blob heap. /// The cumulative size of Blob heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata. /// </param> /// <param name="guidHeapStartOffset"> /// Start offset of the Guid heap. /// The cumulative size of Guid heaps of all previous EnC generations. Should be 0 unless the metadata is EnC delta metadata. /// </param> /// <exception cref="ImageFormatLimitationException">Offset is too big.</exception> /// <exception cref="ArgumentOutOfRangeException">Offset is negative.</exception> /// <exception cref="ArgumentException"><paramref name="guidHeapStartOffset"/> is not a multiple of size of GUID.</exception> public MetadataBuilder( int userStringHeapStartOffset = 0, int stringHeapStartOffset = 0, int blobHeapStartOffset = 0, int guidHeapStartOffset = 0) { // -1 for the 0 we always write at the beginning of the heap: if (userStringHeapStartOffset >= UserStringHeapSizeLimit - 1) { Throw.HeapSizeLimitExceeded(HeapIndex.UserString); } if (userStringHeapStartOffset < 0) { Throw.ArgumentOutOfRange(nameof(userStringHeapStartOffset)); } if (stringHeapStartOffset < 0) { Throw.ArgumentOutOfRange(nameof(stringHeapStartOffset)); } if (blobHeapStartOffset < 0) { Throw.ArgumentOutOfRange(nameof(blobHeapStartOffset)); } if (guidHeapStartOffset < 0) { Throw.ArgumentOutOfRange(nameof(guidHeapStartOffset)); } if (guidHeapStartOffset % BlobUtilities.SizeOfGuid != 0) { throw new ArgumentException(SR.Format(SR.ValueMustBeMultiple, BlobUtilities.SizeOfGuid), nameof(guidHeapStartOffset)); } // Add zero-th entry to all heaps, even in EnC delta. // We don't want generation-relative handles to ever be IsNil. // In both full and delta metadata all nil heap handles should have zero value. // There should be no blob handle that references the 0 byte added at the // beginning of the delta blob. _userStringBuilder.WriteByte(0); _blobs.Add(ImmutableArray<byte>.Empty, default(BlobHandle)); _blobHeapSize = 1; // When EnC delta is applied #US, #String and #Blob heaps are appended. // Thus indices of strings and blobs added to this generation are offset // by the sum of respective heap sizes of all previous generations. _userStringHeapStartOffset = userStringHeapStartOffset; _stringHeapStartOffset = stringHeapStartOffset; _blobHeapStartOffset = blobHeapStartOffset; // Unlike other heaps, #Guid heap in EnC delta is zero-padded. _guidBuilder.WriteBytes(0, guidHeapStartOffset); } /// <summary> /// Sets the capacity of the specified table. /// </summary> /// <param name="heap">Heap index.</param> /// <param name="byteCount">Number of bytes.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="heap"/> is not a valid heap index.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="byteCount"/> is negative.</exception> /// <remarks> /// Use to reduce allocations if the approximate number of bytes is known ahead of time. /// </remarks> public void SetCapacity(HeapIndex heap, int byteCount) { if (byteCount < 0) { Throw.ArgumentOutOfRange(nameof(byteCount)); } switch (heap) { case HeapIndex.Blob: // Not useful to set capacity. // By the time the blob heap is serialized we know the exact size we need. break; case HeapIndex.Guid: _guidBuilder.SetCapacity(byteCount); break; case HeapIndex.String: _stringBuilder.SetCapacity(byteCount); break; case HeapIndex.UserString: _userStringBuilder.SetCapacity(byteCount); break; default: Throw.ArgumentOutOfRange(nameof(heap)); break; } } // internal for testing internal int SerializeHandle(StringHandle handle) => _stringVirtualIndexToHeapOffsetMap[handle.GetWriterVirtualIndex()]; internal int SerializeHandle(BlobHandle handle) => handle.GetHeapOffset(); internal int SerializeHandle(GuidHandle handle) => handle.Index; internal int SerializeHandle(UserStringHandle handle) => handle.GetHeapOffset(); /// <summary> /// Adds specified blob to Blob heap, if it's not there already. /// </summary> /// <param name="value"><see cref="BlobBuilder"/> containing the blob.</param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public BlobHandle GetOrAddBlob(BlobBuilder value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(value.ToImmutableArray()); } /// <summary> /// Adds specified blob to Blob heap, if it's not there already. /// </summary> /// <param name="value">Array containing the blob.</param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public BlobHandle GetOrAddBlob(byte[] value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } // TODO: avoid making a copy if the blob exists in the index return GetOrAddBlob(ImmutableArray.Create(value)); } /// <summary> /// Adds specified blob to Blob heap, if it's not there already. /// </summary> /// <param name="value">Array containing the blob.</param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public BlobHandle GetOrAddBlob(ImmutableArray<byte> value) { if (value.IsDefault) { Throw.ArgumentNull(nameof(value)); } BlobHandle handle; if (!_blobs.TryGetValue(value, out handle)) { Debug.Assert(!HeapsCompleted); handle = BlobHandle.FromOffset(_blobHeapStartOffset + _blobHeapSize); _blobs.Add(value, handle); _blobHeapSize += BlobWriterImpl.GetCompressedIntegerSize(value.Length) + value.Length; } return handle; } /// <summary> /// Encodes a constant value to a blob and adds it to the Blob heap, if it's not there already. /// Uses UTF16 to encode string constants. /// </summary> /// <param name="value">Constant value.</param> /// <returns>Handle to the added or existing blob.</returns> public unsafe BlobHandle GetOrAddConstantBlob(object value) { string str = value as string; if (str != null) { return GetOrAddBlobUTF16(str); } var builder = PooledBlobBuilder.GetInstance(); builder.WriteConstant(value); var result = GetOrAddBlob(builder); builder.Free(); return result; } /// <summary> /// Encodes a string using UTF16 encoding to a blob and adds it to the Blob heap, if it's not there already. /// </summary> /// <param name="value">String.</param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public BlobHandle GetOrAddBlobUTF16(string value) { var builder = PooledBlobBuilder.GetInstance(); builder.WriteUTF16(value); var handle = GetOrAddBlob(builder); builder.Free(); return handle; } /// <summary> /// Encodes a string using UTF8 encoding to a blob and adds it to the Blob heap, if it's not there already. /// </summary> /// <param name="value">Constant value.</param> /// <param name="allowUnpairedSurrogates"> /// True to encode unpaired surrogates as specified, otherwise replace them with U+FFFD character. /// </param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public BlobHandle GetOrAddBlobUTF8(string value, bool allowUnpairedSurrogates = true) { var builder = PooledBlobBuilder.GetInstance(); builder.WriteUTF8(value, allowUnpairedSurrogates); var handle = GetOrAddBlob(builder); builder.Free(); return handle; } /// <summary> /// Adds specified Guid to Guid heap, if it's not there already. /// </summary> /// <param name="guid">Guid to add.</param> /// <returns>Handle to the added or existing Guid.</returns> public GuidHandle GetOrAddGuid(Guid guid) { if (guid == Guid.Empty) { return default(GuidHandle); } GuidHandle result; if (_guids.TryGetValue(guid, out result)) { return result; } result = GetNewGuidHandle(); _guids.Add(guid, result); _guidBuilder.WriteGuid(guid); return result; } /// <summary> /// Reserves space on the Guid heap for a GUID. /// </summary> /// <param name="content"> /// <see cref="Blob"/> representing the GUID blob as stored on the heap. /// </param> /// <returns>Handle to the reserved Guid.</returns> /// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception> public GuidHandle ReserveGuid(out Blob content) { var handle = GetNewGuidHandle(); content = _guidBuilder.ReserveBytes(BlobUtilities.SizeOfGuid); return handle; } private GuidHandle GetNewGuidHandle() { Debug.Assert(!HeapsCompleted); // Unlike #Blob, #String and #US streams delta #GUID stream is padded to the // size of the previous generation #GUID stream before new GUIDs are added. // The first GUID added in a delta will thus have an index that equals the number // of GUIDs in all previous generations + 1. // Metadata Spec: // The Guid heap is an array of GUIDs, each 16 bytes wide. // Its first element is numbered 1, its second 2, and so on. return GuidHandle.FromIndex((_guidBuilder.Count >> 4) + 1); } /// <summary> /// Adds specified string to String heap, if it's not there already. /// </summary> /// <param name="value">Array containing the blob.</param> /// <returns>Handle to the added or existing blob.</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public StringHandle GetOrAddString(string value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } StringHandle handle; if (value.Length == 0) { handle = default(StringHandle); } else if (!_strings.TryGetValue(value, out handle)) { Debug.Assert(!HeapsCompleted); handle = StringHandle.FromWriterVirtualIndex(_strings.Count + 1); // idx 0 is reserved for empty string _strings.Add(value, handle); } return handle; } /// <summary> /// Reserves space on the User String heap for a string of specified length. /// </summary> /// <param name="length">The number of characters to reserve.</param> /// <param name="reservedUserString"> /// <see cref="Blob"/> representing the entire User String blob (including its length and terminal character). /// Use <see cref="BlobWriter.WriteUserString(string)"/> to fill in the content. /// </param> /// <returns> /// Handle to the reserved User String. /// May be used in <see cref="InstructionEncoder.LoadString(UserStringHandle)"/>. /// </returns> /// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is negative.</exception> public UserStringHandle ReserveUserString(int length, out Blob reservedUserString) { if (length < 0) { Throw.ArgumentOutOfRange(nameof(length)); } var handle = GetNewUserStringHandle(); int encodedLength = BlobUtilities.GetUserStringByteLength(length); reservedUserString = _userStringBuilder.ReserveBytes(BlobWriterImpl.GetCompressedIntegerSize(encodedLength) + encodedLength); return handle; } /// <summary> /// Adds specified string to User String heap, if it's not there already. /// </summary> /// <param name="value">String to add.</param> /// <returns> /// Handle to the added or existing string. /// May be used in <see cref="InstructionEncoder.LoadString(UserStringHandle)"/>. /// </returns> /// <exception cref="ImageFormatLimitationException">The remaining space on the heap is too small to fit the string.</exception> /// <exception cref="ArgumentNullException"><paramref name="value"/> is null.</exception> public UserStringHandle GetOrAddUserString(string value) { if (value == null) { Throw.ArgumentNull(nameof(value)); } UserStringHandle handle; if (!_userStrings.TryGetValue(value, out handle)) { Debug.Assert(!HeapsCompleted); handle = GetNewUserStringHandle(); _userStrings.Add(value, handle); _userStringBuilder.WriteUserString(value); } return handle; } private UserStringHandle GetNewUserStringHandle() { int offset = _userStringHeapStartOffset + _userStringBuilder.Count; // Native metadata emitter allows strings to exceed the heap size limit as long // as the index is within the limits (see https://github.com/dotnet/roslyn/issues/9852) if (offset >= UserStringHeapSizeLimit) { Throw.HeapSizeLimitExceeded(HeapIndex.UserString); } return UserStringHandle.FromOffset(offset); } internal void CompleteHeaps() { Debug.Assert(!HeapsCompleted); SerializeStringHeap(); } public ImmutableArray<int> GetHeapSizes() { var heapSizes = new int[MetadataTokens.HeapCount]; heapSizes[(int)HeapIndex.UserString] = _userStringBuilder.Count; heapSizes[(int)HeapIndex.String] = _stringBuilder.Count; heapSizes[(int)HeapIndex.Blob] = _blobHeapSize; heapSizes[(int)HeapIndex.Guid] = _guidBuilder.Count; return ImmutableArray.CreateRange(heapSizes); } /// <summary> /// Fills in stringIndexMap with data from stringIndex and write to stringWriter. /// Releases stringIndex as the stringTable is sealed after this point. /// </summary> private void SerializeStringHeap() { // Sort by suffix and remove stringIndex var sorted = new List<KeyValuePair<string, StringHandle>>(_strings); sorted.Sort(new SuffixSort()); _strings = null; // Create VirtIdx to Idx map and add entry for empty string _stringVirtualIndexToHeapOffsetMap = new int[sorted.Count + 1]; _stringVirtualIndexToHeapOffsetMap[0] = 0; _stringBuilder.WriteByte(0); // Find strings that can be folded string prev = string.Empty; foreach (KeyValuePair<string, StringHandle> entry in sorted) { int position = _stringHeapStartOffset + _stringBuilder.Count; // It is important to use ordinal comparison otherwise we'll use the current culture! if (prev.EndsWith(entry.Key, StringComparison.Ordinal) && !BlobUtilities.IsLowSurrogateChar(entry.Key[0])) { // Map over the tail of prev string. Watch for null-terminator of prev string. _stringVirtualIndexToHeapOffsetMap[entry.Value.GetWriterVirtualIndex()] = position - (BlobUtilities.GetUTF8ByteCount(entry.Key) + 1); } else { _stringVirtualIndexToHeapOffsetMap[entry.Value.GetWriterVirtualIndex()] = position; _stringBuilder.WriteUTF8(entry.Key, allowUnpairedSurrogates: false); _stringBuilder.WriteByte(0); } prev = entry.Key; } } /// <summary> /// Sorts strings such that a string is followed immediately by all strings /// that are a suffix of it. /// </summary> private sealed class SuffixSort : IComparer<KeyValuePair<string, StringHandle>> { public int Compare(KeyValuePair<string, StringHandle> xPair, KeyValuePair<string, StringHandle> yPair) { string x = xPair.Key; string y = yPair.Key; for (int i = x.Length - 1, j = y.Length - 1; i >= 0 & j >= 0; i--, j--) { if (x[i] < y[j]) { return -1; } if (x[i] > y[j]) { return +1; } } return y.Length.CompareTo(x.Length); } } internal void WriteHeapsTo(BlobBuilder builder) { Debug.Assert(HeapsCompleted); WriteAligned(_stringBuilder, builder); WriteAligned(_userStringBuilder, builder); WriteAligned(_guidBuilder, builder); WriteAlignedBlobHeap(builder); } private void WriteAlignedBlobHeap(BlobBuilder builder) { int alignment = BitArithmetic.Align(_blobHeapSize, 4) - _blobHeapSize; var writer = new BlobWriter(builder.ReserveBytes(_blobHeapSize + alignment)); // Perf consideration: With large heap the following loop may cause a lot of cache misses // since the order of entries in _blobs dictionary depends on the hash of the array values, // which is not correlated to the heap index. If we observe such issue we should order // the entries by heap position before running this loop. int startOffset = _blobHeapStartOffset; foreach (var entry in _blobs) { int heapOffset = entry.Value.GetHeapOffset(); var blob = entry.Key; writer.Offset = (heapOffset == 0) ? 0 : heapOffset - startOffset; writer.WriteCompressedInteger(blob.Length); writer.WriteBytes(blob); } writer.Offset = _blobHeapSize; writer.WriteBytes(0, alignment); } private static void WriteAligned(BlobBuilder source, BlobBuilder target) { int length = source.Count; target.LinkSuffix(source); target.WriteBytes(0, BitArithmetic.Align(length, 4) - length); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: Contains the business logic for symbology layers and symbol categories. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 10/11/2009 10:24:02 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using DotSpatial.Serialization; namespace DotSpatial.Symbology { public class Category : LegendItem { #region Private Variables private Range _range; #endregion #region Constructors /// <summary> /// Creates a new instance of Category /// </summary> public Category() { } /// <summary> /// Creaates a new instance of this category, and tailors the range to the specifeid values. /// </summary> /// <param name="startValue">The start value</param> /// <param name="endValue">The end value</param> public Category(double? startValue, double? endValue) { _range = new Range(startValue, endValue); } /// <summary> /// Creates a category that has the same value for both minimum and maximum /// </summary> /// <param name="value">The value to use</param> public Category(double value) { _range = new Range(value); } #endregion #region Methods /// <summary> /// Applies the snapping rule directly to the categories, instead of the breaks. /// </summary> public void ApplySnapping(IntervalSnapMethod method, int numDigits, List<double> values) { switch (method) { case IntervalSnapMethod.None: break; case IntervalSnapMethod.SignificantFigures: if (Maximum != null) { Maximum = SigFig(Maximum.Value, numDigits); } if (Minimum != null) { Minimum = SigFig(Minimum.Value, numDigits); } break; case IntervalSnapMethod.Rounding: if (Maximum != null) { Maximum = Math.Round((double)Maximum, numDigits); } if (Minimum != null) { Minimum = Math.Round((double)Minimum, numDigits); } break; case IntervalSnapMethod.DataValue: if (Maximum != null) { Maximum = NearestValue((double)Maximum, values); } if (Minimum != null) { Minimum = NearestValue((double)Minimum, values); } break; } } private static double SigFig(double value, int numFigures) { int md = (int)Math.Ceiling(Math.Log10(Math.Abs(value))); md -= numFigures; double norm = Math.Pow(10, md); return norm * Math.Round(value / norm); } /// <summary> /// Searches the list and returns the nearest value in the list to the specified value. /// </summary> /// <param name="value"></param> /// <param name="values"></param> /// <returns></returns> private static double NearestValue(double value, List<double> values) { return GetNearestValue(value, values); } /// <summary> /// Since rasters are numeric and not relying on an SQL expression, this allows /// this only sets the legend text using the method and digits to help with /// formatting. /// </summary> /// <param name="settings">An EditorSettings from either a feature scheme or color scheme.</param> public virtual void ApplyMinMax(EditorSettings settings) { LegendText = Range.ToString(settings.IntervalSnapMethod, settings.IntervalRoundingDigits); } /// <summary> /// Tests to see if the specified value falls in the range specified by this ColorCategory /// </summary> /// <param name="value">The value of type int to test</param> /// <returns>Boolean, true if the value was found in the range</returns> public bool Contains(double value) { return _range == null || _range.Contains(value); } /// <summary> /// Returns this Number as a string. This uses the DotSpatial.Globalization.CulturePreferences and /// Controls the number type using the NumberFormat enumeration plus the DecimalCount to create /// a number format. /// </summary> /// <returns>The string created using the specified number format and precision.</returns> public override string ToString() { return _range.ToString(); } /// <summary> /// Returns this Number as a string. /// </summary> /// <param name="method">Specifies how the numbers are modified so that the numeric text can be cleaned up.</param> /// <param name="digits">An integer clarifying digits for rounding or significant figure situations.</param> /// <returns>A string with the formatted number.</returns> public virtual string ToString(IntervalSnapMethod method, int digits) { return _range.ToString(method, digits); } #endregion #region Properties /// <summary> /// Maximum this is a convenient caching tool only, and doesn't control the filter expression at all. /// Use ApplyMinMax after setting this to update the filter expression. /// </summary> [Description("Gets or sets the maximum value for this category using the scheme field.")] public double? Maximum { get { return _range != null ? _range.Maximum : null; } set { if (_range == null) { _range = new Range(null, value); return; } _range.Maximum = value; } } /// <summary> /// Gets or sets the color to be used for this break. For /// BiValued breaks, this only sets one of the colors. If /// this is higher than the high value, both are set to this. /// If this equals the high value, IsBiValue will be false. /// </summary> [Description("Gets or sets a minimum value for this category using the scheme field.")] public double? Minimum { get { return _range != null ? _range.Minimum : null; } set { if (_range == null) { _range = new Range(value, null); return; } _range.Minimum = value; } } /// <summary> /// Gets the numeric Range for this color break. /// </summary> [Serialize("Range")] public Range Range { get { return _range; } set { _range = value; } } /// <summary> /// Gets or sets a status message for this string. /// </summary> public string Status { get; set; } /// <summary> /// This is not used by DotSpatial, but is provided for convenient linking for this object /// in plugins or other applications. /// </summary> public object Tag { get; set; } #endregion } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Configuration; using Orleans.Transactions; namespace Orleans.Runtime { /// <summary> /// This interface is for use with the Orleans timers. /// </summary> internal interface ITimebound { /// <summary> /// This method is called by the timer when the time out is reached. /// </summary> void OnTimeout(); TimeSpan RequestedTimeout(); } internal class CallbackData : ITimebound, IDisposable { private readonly Action<Message, TaskCompletionSource<object>> callback; private readonly Func<Message, bool> resendFunc; private readonly Action<Message> unregister; private readonly TaskCompletionSource<object> context; private readonly MessagingOptions messagingOptions; private bool alreadyFired; private TimeSpan timeout; private SafeTimer timer; private ITimeInterval timeSinceIssued; private readonly ILogger logger; private readonly ILogger timerLogger; private readonly ApplicationRequestsStatisticsGroup requestStatistics; public ITransactionInfo TransactionInfo { get; set; } public Message Message { get; set; } // might hold metadata used by response pipeline public CallbackData( Action<Message, TaskCompletionSource<object>> callback, Func<Message, bool> resendFunc, TaskCompletionSource<object> ctx, Message msg, Action<Message> unregisterDelegate, MessagingOptions messagingOptions, ILogger logger, ILogger timerLogger, ApplicationRequestsStatisticsGroup requestStatistics) { // We are never called without a callback func, but best to double check. if (callback == null) throw new ArgumentNullException(nameof(callback)); // We are never called without a resend func, but best to double check. if (resendFunc == null) throw new ArgumentNullException(nameof(resendFunc)); this.logger = logger; this.callback = callback; this.resendFunc = resendFunc; context = ctx; Message = msg; unregister = unregisterDelegate; alreadyFired = false; this.messagingOptions = messagingOptions; this.TransactionInfo = TransactionContext.GetTransactionInfo(); this.timerLogger = timerLogger; this.requestStatistics = requestStatistics; } /// <summary> /// Start this callback timer /// </summary> /// <param name="time">Timeout time</param> public void StartTimer(TimeSpan time) { if (time < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(time), "The timeout parameter is negative."); timeout = time; if (this.requestStatistics.CollectApplicationRequestsStats) { timeSinceIssued = TimeIntervalFactory.CreateTimeInterval(true); timeSinceIssued.Start(); } TimeSpan firstPeriod = timeout; TimeSpan repeatPeriod = Constants.INFINITE_TIMESPAN; // Single timeout period --> No repeat if (messagingOptions.ResendOnTimeout && messagingOptions.MaxResendCount > 0) { firstPeriod = repeatPeriod = timeout.Divide(messagingOptions.MaxResendCount + 1); } // Start time running DisposeTimer(); timer = new SafeTimer(this.timerLogger, TimeoutCallback, null, firstPeriod, repeatPeriod); } private void TimeoutCallback(object obj) { OnTimeout(); } public void OnTimeout() { if (alreadyFired) return; var msg = Message; // Local working copy string messageHistory = msg.GetTargetHistory(); string errorMsg = $"Response did not arrive on time in {timeout} for message: {msg}. Target History is: {messageHistory}."; logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg); var error = Message.CreatePromptExceptionResponse(msg, new TimeoutException(errorMsg)); OnFail(msg, error, "OnTimeout - Resend {0} for {1}", true); } public void OnTargetSiloFail() { if (alreadyFired) return; var msg = Message; var messageHistory = msg.GetTargetHistory(); string errorMsg = $"The target silo became unavailable for message: {msg}. Target History is: {messageHistory}. See {Constants.TroubleshootingHelpLink} for troubleshooting help."; logger.Warn(ErrorCode.Runtime_Error_100157, "{0} About to break its promise.", errorMsg); var error = Message.CreatePromptExceptionResponse(msg, new SiloUnavailableException(errorMsg)); OnFail(msg, error, "On silo fail - Resend {0} for {1}"); } public void DoCallback(Message response) { if (alreadyFired) return; lock (this) { if (alreadyFired) return; if (response.Result == Message.ResponseTypes.Rejection && response.RejectionType == Message.RejectionTypes.Transient) { if (resendFunc(Message)) { return; } } alreadyFired = true; DisposeTimer(); if (this.requestStatistics.CollectApplicationRequestsStats) { timeSinceIssued.Stop(); } unregister?.Invoke(Message); } if (this.requestStatistics.CollectApplicationRequestsStats) { this.requestStatistics.OnAppRequestsEnd(timeSinceIssued.Elapsed); } // do callback outside the CallbackData lock. Just not a good practice to hold a lock for this unrelated operation. callback(response, context); } public void Dispose() { DisposeTimer(); GC.SuppressFinalize(this); } private void DisposeTimer() { try { var tmp = timer; if (tmp != null) { timer = null; tmp.Dispose(); } } catch (Exception) { } // Ignore any problems with Dispose } private void OnFail(Message msg, Message error, string resendLogMessageFormat, bool isOnTimeout = false) { lock (this) { if (alreadyFired) return; if (messagingOptions.ResendOnTimeout && resendFunc(msg)) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(resendLogMessageFormat, msg.ResendCount, msg); return; } alreadyFired = true; DisposeTimer(); if (this.requestStatistics.CollectApplicationRequestsStats) { timeSinceIssued.Stop(); } unregister?.Invoke(Message); } if (this.requestStatistics.CollectApplicationRequestsStats) { this.requestStatistics.OnAppRequestsEnd(timeSinceIssued.Elapsed); if (isOnTimeout) { this.requestStatistics.OnAppRequestsTimedOut(); } } callback(error, context); } public TimeSpan RequestedTimeout() { return timeout; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.InteropServices; using Xunit; namespace System.Net.Tests { public class WebProxyTest { public static IEnumerable<object[]> Ctor_ExpectedPropertyValues_MemberData() { yield return new object[] { new WebProxy(), null, false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything"), new Uri("http://anything"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("anything", 42), new Uri("http://anything:42"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy(new Uri("http://anything")), new Uri("http://anything"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything", true), new Uri("http://anything"), false, true, Array.Empty<string>(), null }; yield return new object[] { new WebProxy(new Uri("http://anything"), true), new Uri("http://anything"), false, true, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null }; yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null }; var c = new DummyCredentials(); yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c }; yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c }; } [Theory] [MemberData(nameof(Ctor_ExpectedPropertyValues_MemberData))] public static void WebProxy_Ctor_ExpectedPropertyValues( WebProxy p, Uri address, bool useDefaultCredentials, bool bypassLocal, string[] bypassedAddresses, ICredentials creds) { Assert.Equal(address, p.Address); Assert.Equal(useDefaultCredentials, p.UseDefaultCredentials); Assert.Equal(bypassLocal, p.BypassProxyOnLocal); Assert.Equal(bypassedAddresses, p.BypassList); Assert.Equal(bypassedAddresses, (string[])p.BypassArrayList.ToArray(typeof(string))); Assert.Equal(creds, p.Credentials); } [Fact] public static void WebProxy_BypassList_Roundtrip() { var p = new WebProxy(); Assert.Empty(p.BypassList); Assert.Empty(p.BypassArrayList); string[] strings; strings = new string[] { "hello", "world" }; p.BypassList = strings; Assert.Equal(strings, p.BypassList); Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string))); strings = new string[] { "hello" }; p.BypassList = strings; Assert.Equal(strings, p.BypassList); Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string))); } [Fact] public static void WebProxy_UseDefaultCredentials_Roundtrip() { var p = new WebProxy(); Assert.False(p.UseDefaultCredentials); Assert.Null(p.Credentials); p.UseDefaultCredentials = true; Assert.True(p.UseDefaultCredentials); Assert.NotNull(p.Credentials); p.UseDefaultCredentials = false; Assert.False(p.UseDefaultCredentials); Assert.Null(p.Credentials); } [Fact] public static void WebProxy_BypassProxyOnLocal_Roundtrip() { var p = new WebProxy(); Assert.False(p.BypassProxyOnLocal); p.BypassProxyOnLocal = true; Assert.True(p.BypassProxyOnLocal); p.BypassProxyOnLocal = false; Assert.False(p.BypassProxyOnLocal); } [Fact] public static void WebProxy_Address_Roundtrip() { var p = new WebProxy(); Assert.Null(p.Address); p.Address = new Uri("http://hello"); Assert.Equal(new Uri("http://hello"), p.Address); p.Address = null; Assert.Null(p.Address); } [Fact] public static void WebProxy_InvalidArgs_Throws() { var p = new WebProxy(); AssertExtensions.Throws<ArgumentNullException>("destination", () => p.GetProxy(null)); AssertExtensions.Throws<ArgumentNullException>("host", () => p.IsBypassed(null)); AssertExtensions.Throws<ArgumentNullException>("c", () => p.BypassList = null); Assert.ThrowsAny<ArgumentException>(() => p.BypassList = new string[] { "*.com" }); } [Fact] public static void WebProxy_InvalidBypassUrl_AddedDirectlyToList_SilentlyEaten() { var p = new WebProxy("http://bing.com"); p.BypassArrayList.Add("*.com"); p.IsBypassed(new Uri("http://microsoft.com")); // exception should be silently eaten } [Fact] public static void WebProxy_BypassList_DoesntContainUrl_NotBypassed() { var p = new WebProxy("http://microsoft.com"); Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com"))); } [Fact] public static void WebProxy_BypassList_ContainsUrl_IsBypassed() { var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" }); Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com"))); } public static IEnumerable<object[]> BypassOnLocal_MemberData() { // Local yield return new object[] { new Uri($"http://nodotinhostname"), true }; yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}"), true }; foreach (IPAddress address in Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { Uri uri; try { uri = new Uri($"http://{address}"); } catch (UriFormatException) { continue; } yield return new object[] { uri, true }; } } string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName; if (!string.IsNullOrWhiteSpace(domain)) { Uri uri = null; try { uri = new Uri($"http://{Guid.NewGuid().ToString("N")}.{domain}"); } catch (UriFormatException) { } if (uri != null) { yield return new object[] { uri, true }; } } // Non-local yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}.com"), false }; yield return new object[] { new Uri($"http://{IPAddress.None}"), false }; } [ActiveIssue(23766, TestPlatforms.AnyUnix)] [Theory] [MemberData(nameof(BypassOnLocal_MemberData))] public static void WebProxy_BypassOnLocal_MatchesExpected(Uri destination, bool isLocal) { Uri proxyUri = new Uri("http://microsoft.com"); try { Assert.Equal(isLocal, new WebProxy(proxyUri, true).IsBypassed(destination)); Assert.False(new WebProxy(proxyUri, false).IsBypassed(destination)); Assert.Equal(isLocal ? destination : proxyUri, new WebProxy(proxyUri, true).GetProxy(destination)); Assert.Equal(proxyUri, new WebProxy(proxyUri, false).GetProxy(destination)); } catch (SocketException exception) { // On Unix, getaddrinfo returns host not found, if all the machine discovery settings on the local network // is turned off. Hence dns lookup for it's own hostname fails. Assert.Equal(SocketError.HostNotFound, exception.SocketErrorCode); Assert.Throws<SocketException>(() => Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult()); Assert.True(RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); } } [Fact] public static void WebProxy_BypassOnLocal_SpecialCases() { Assert.True(new WebProxy().IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy((string)null).IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy((Uri)null).IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy("microsoft", BypassOnLocal: true).IsBypassed(new Uri($"http://{IPAddress.Loopback}"))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Not yet fixed in the .NET framework")] public static void WebProxy_BypassOnLocal_ConfiguredToNotBypassLocal() { Assert.False(new WebProxy("microsoft", BypassOnLocal: false).IsBypassed(new Uri($"http://{IPAddress.Loopback}"))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void WebProxy_GetDefaultProxy_NotSupported() { #pragma warning disable 0618 // obsolete method Assert.Throws<PlatformNotSupportedException>(() => WebProxy.GetDefaultProxy()); #pragma warning restore 0618 } private class DummyCredentials : ICredentials { public NetworkCredential GetCredential(Uri uri, string authType) => null; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Reflection; using Nini.Config; namespace OpenSim.Region.PhysicsModule.BulletS { public struct MaterialAttributes { // Material type values that correspond with definitions for LSL public enum Material : int { Stone = 0, Metal, Glass, Wood, Flesh, Plastic, Rubber, Light, // Hereafter are BulletSim additions Avatar, NumberOfTypes // the count of types in the enum. } // Names must be in the order of the above enum. // These names must coorespond to the lower case field names in the MaterialAttributes // structure as reflection is used to select the field to put the value in. public static readonly string[] MaterialAttribs = { "Density", "Friction", "Restitution"}; public MaterialAttributes(string t, float d, float f, float r) { type = t; density = d; friction = f; restitution = r; } public string type; public float density; public float friction; public float restitution; } public static class BSMaterials { // Attributes for each material type private static readonly MaterialAttributes[] Attributes; // Map of material name to material type code public static readonly Dictionary<string, MaterialAttributes.Material> MaterialMap; static BSMaterials() { // Attribute sets for both the non-physical and physical instances of materials. Attributes = new MaterialAttributes[(int)MaterialAttributes.Material.NumberOfTypes * 2]; // Map of name to type code. MaterialMap = new Dictionary<string, MaterialAttributes.Material>(); MaterialMap.Add("Stone", MaterialAttributes.Material.Stone); MaterialMap.Add("Metal", MaterialAttributes.Material.Metal); MaterialMap.Add("Glass", MaterialAttributes.Material.Glass); MaterialMap.Add("Wood", MaterialAttributes.Material.Wood); MaterialMap.Add("Flesh", MaterialAttributes.Material.Flesh); MaterialMap.Add("Plastic", MaterialAttributes.Material.Plastic); MaterialMap.Add("Rubber", MaterialAttributes.Material.Rubber); MaterialMap.Add("Light", MaterialAttributes.Material.Light); MaterialMap.Add("Avatar", MaterialAttributes.Material.Avatar); } // This is where all the default material attributes are defined. public static void InitializeFromDefaults(ConfigurationParameters parms) { // Values from http://wiki.secondlife.com/wiki/PRIM_MATERIAL float dDensity = parms.defaultDensity; float dFriction = parms.defaultFriction; float dRestitution = parms.defaultRestitution; Attributes[(int)MaterialAttributes.Material.Stone] = new MaterialAttributes("stone",dDensity, 0.8f, 0.4f); Attributes[(int)MaterialAttributes.Material.Metal] = new MaterialAttributes("metal",dDensity, 0.3f, 0.4f); Attributes[(int)MaterialAttributes.Material.Glass] = new MaterialAttributes("glass",dDensity, 0.2f, 0.7f); Attributes[(int)MaterialAttributes.Material.Wood] = new MaterialAttributes("wood",dDensity, 0.6f, 0.5f); Attributes[(int)MaterialAttributes.Material.Flesh] = new MaterialAttributes("flesh",dDensity, 0.9f, 0.3f); Attributes[(int)MaterialAttributes.Material.Plastic] = new MaterialAttributes("plastic",dDensity, 0.4f, 0.7f); Attributes[(int)MaterialAttributes.Material.Rubber] = new MaterialAttributes("rubber",dDensity, 0.9f, 0.9f); Attributes[(int)MaterialAttributes.Material.Light] = new MaterialAttributes("light",dDensity, dFriction, dRestitution); Attributes[(int)MaterialAttributes.Material.Avatar] = new MaterialAttributes("avatar",3.5f, 0.2f, 0f); Attributes[(int)MaterialAttributes.Material.Stone + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("stonePhysical",dDensity, 0.8f, 0.4f); Attributes[(int)MaterialAttributes.Material.Metal + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("metalPhysical",dDensity, 0.3f, 0.4f); Attributes[(int)MaterialAttributes.Material.Glass + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("glassPhysical",dDensity, 0.2f, 0.7f); Attributes[(int)MaterialAttributes.Material.Wood + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("woodPhysical",dDensity, 0.6f, 0.5f); Attributes[(int)MaterialAttributes.Material.Flesh + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("fleshPhysical",dDensity, 0.9f, 0.3f); Attributes[(int)MaterialAttributes.Material.Plastic + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("plasticPhysical",dDensity, 0.4f, 0.7f); Attributes[(int)MaterialAttributes.Material.Rubber + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("rubberPhysical",dDensity, 0.9f, 0.9f); Attributes[(int)MaterialAttributes.Material.Light + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("lightPhysical",dDensity, dFriction, dRestitution); Attributes[(int)MaterialAttributes.Material.Avatar + (int)MaterialAttributes.Material.NumberOfTypes] = new MaterialAttributes("avatarPhysical",3.5f, 0.2f, 0f); } // Under the [BulletSim] section, one can change the individual material // attribute values. The format of the configuration parameter is: // <materialName><Attribute>["Physical"] = floatValue // For instance: // [BulletSim] // StoneFriction = 0.2 // FleshRestitutionPhysical = 0.8 // Materials can have different parameters for their static and // physical instantiations. When setting the non-physical value, // both values are changed. Setting the physical value only changes // the physical value. public static void InitializefromParameters(IConfig pConfig) { foreach (KeyValuePair<string, MaterialAttributes.Material> kvp in MaterialMap) { string matName = kvp.Key; foreach (string attribName in MaterialAttributes.MaterialAttribs) { string paramName = matName + attribName; if (pConfig.Contains(paramName)) { float paramValue = pConfig.GetFloat(paramName); SetAttributeValue((int)kvp.Value, attribName, paramValue); // set the physical value also SetAttributeValue((int)kvp.Value + (int)MaterialAttributes.Material.NumberOfTypes, attribName, paramValue); } paramName += "Physical"; if (pConfig.Contains(paramName)) { float paramValue = pConfig.GetFloat(paramName); SetAttributeValue((int)kvp.Value + (int)MaterialAttributes.Material.NumberOfTypes, attribName, paramValue); } } } } // Use reflection to set the value in the attribute structure. private static void SetAttributeValue(int matType, string attribName, float val) { // Get the current attribute values for this material MaterialAttributes thisAttrib = Attributes[matType]; // Find the field for the passed attribute name (eg, find field named 'friction') FieldInfo fieldInfo = thisAttrib.GetType().GetField(attribName.ToLower()); if (fieldInfo != null) { fieldInfo.SetValue(thisAttrib, val); // Copy new attributes back to array -- since MaterialAttributes is 'struct', passed by value, not reference. Attributes[matType] = thisAttrib; } } // Given a material type, return a structure of attributes. public static MaterialAttributes GetAttributes(MaterialAttributes.Material type, bool isPhysical) { int ind = (int)type; if (isPhysical) ind += (int)MaterialAttributes.Material.NumberOfTypes; return Attributes[ind]; } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; //additional using statements using System.Windows.Forms; using System.IO; namespace CharacterCustomizer { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont sf; List<Wheel> characterParts;//all the character component wheels Die die; MiscButton previewButton, saveButton, loadButton; MouseState mouseState, prevMouseState;//current and previous mouse state Preview preview = null; Texture2D saving, save; string loadedFile; const int WHEEL_SCALE = 6; const int DIE_SCALE = 4; public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; } /// <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() { // TODO: Add your initialization logic here this.IsMouseVisible = true; //graphics.PreferMultiSampling = false; //graphics.ApplyChanges(); mouseState = Mouse.GetState(); characterParts = new List<Wheel>(); int x = 20; int y = 50; characterParts.Add(new Wheel(WHEEL_SCALE, "Faces", Content, x + 50, y)); y += 20 * WHEEL_SCALE; characterParts.Add(new LongWheel(WHEEL_SCALE, "Bodies", Content, x + 20, y - 20, 2, 1.5, 1)); y += 20 * WHEEL_SCALE; characterParts.Add(new LongWheel(WHEEL_SCALE, "Legs", Content, x + 35, y, 1.5, 1.5, 1.5)); die = new Die(DIE_SCALE, 500, 100, Content); previewButton = new MiscButton(500, 300, "Buttons/Preview", Content, 3); saveButton = new MiscButton(500, 350, "Buttons/Save", Content, 3); save = saveButton.Button; loadButton = new MiscButton(500, 400, "Buttons/Load", Content, 3); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); // TODO: use this.Content to load your game content here sf = Content.Load<SpriteFont>("SpriteFont1"); die.StatText = sf; saving = Content.Load<Texture2D>("Buttons/Saving"); } /// <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 == Microsoft.Xna.Framework.Input.ButtonState.Pressed) this.Exit(); // TODO: Add your update logic here prevMouseState = mouseState; mouseState = Mouse.GetState(); if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed && prevMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released) { if (preview != null) preview.ButtonClick(mouseState.X, mouseState.Y); else { foreach (Wheel characterPart in characterParts) characterPart.ButtonClick(mouseState.X, mouseState.Y); die.ButtonClick(mouseState.X, mouseState.Y); previewButton.ButtonClick(mouseState.X, mouseState.Y); saveButton.ButtonClick(mouseState.X, mouseState.Y); loadButton.ButtonClick(mouseState.X, mouseState.Y); } } else if (mouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released && prevMouseState.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed) { if (preview != null) preview.ButtonUnClick(); else { foreach (Wheel characterPart in characterParts) characterPart.ButtonUnClick(); die.ButtonUnClick(); previewButton.ButtonUnClick(); saveButton.ButtonUnClick(); loadButton.ButtonUnClick(); } } if (previewButton.Clicked) { preview = new Preview(characterParts[0].Current, characterParts[0].Color, characterParts[1].Current, characterParts[1].Color, characterParts[2].Current, characterParts[2].Color, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height, Content); previewButton.ButtonUnClick(); } if (saveButton.Clicked) { saveButton.Button = saving; Save(); saveButton.ButtonUnClick(); saveButton.Button = save; } if (loadButton.Clicked) { Load(); loadButton.ButtonUnClick(); } if (preview != null && preview.Clicked) preview = null; 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) { GraphicsDevice.Clear(Color.MediumPurple); // TODO: Add your drawing code here //this overload turns off antialiasing spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.PointClamp, DepthStencilState.Default, RasterizerState.CullNone, null, Matrix.Identity); foreach (Wheel characterPart in characterParts) characterPart.Draw(spriteBatch); die.Draw(spriteBatch); previewButton.Draw(spriteBatch); saveButton.Draw(spriteBatch); loadButton.Draw(spriteBatch); if (preview != null) { preview.Draw(spriteBatch); } spriteBatch.End(); base.Draw(gameTime); } public void Save() { SaveFileDialog saver = new SaveFileDialog(); saver.AddExtension = true; saver.CheckPathExists = true; saver.DefaultExt = "dat"; saver.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + "Saves\\"; saver.OverwritePrompt = true; saver.RestoreDirectory = true; saver.Title = "Save Character As"; if (loadedFile != null) saver.FileName = loadedFile; if (saver.ShowDialog() == DialogResult.OK) { using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(saver.FileName))) { try { foreach (Wheel w in characterParts) bw.Write(w.Save()); foreach (int stat in die.Save()) bw.Write(stat); } catch (Exception e) { Console.WriteLine(e.Message); } finally { if (bw != null) bw.Dispose(); } } } loadedFile = saver.FileName; if (saver != null) saver.Dispose(); } public void Load() { OpenFileDialog loader = new OpenFileDialog(); loader.CheckPathExists = true; loader.CheckFileExists = true; //loader.DefaultExt = "dat"; loader.Filter = "Data files (.dat)|*.dat|All files|*.*"; loader.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + "Saves\\"; loader.RestoreDirectory = true; loader.Title = "Load Character"; if (loader.ShowDialog() == DialogResult.OK) { using (BinaryReader br = new BinaryReader(File.OpenRead(loader.FileName))) { try { foreach (Wheel w in characterParts) w.Load(br.ReadString()); List<int> stats = new List<int>(); foreach (int stat in die.Save()) stats.Add(br.ReadInt32()); die.Load(stats); } catch (Exception e) { Console.WriteLine(e.Message); } finally { if (br != null) br.Dispose(); } } } loadedFile = loader.FileName; if (loader != null) loader.Dispose(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Text; namespace Microsoft.Azure.Batch { using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models = Microsoft.Azure.Batch.Protocol.Models; /// <summary> /// Summarizes the state of a compute node. /// </summary> public partial class ComputeNode : IRefreshable { #region ComputeNode /// <summary> /// Instantiates an unbound ComputeNodeUser object to be populated by the caller and used to create a user account on the compute node in the Azure Batch service. /// </summary> /// <returns>An <see cref="ComputeNodeUser"/> object.</returns> public ComputeNodeUser CreateComputeNodeUser() { ComputeNodeUser newUser = new ComputeNodeUser(this.parentBatchClient, this.CustomBehaviors, this.parentPoolId, this.Id); return newUser; } /// <summary> /// Begins an asynchronous call to delete the specified ComputeNodeUser. /// </summary> /// <param name="userName">The name of the ComputeNodeUser to be deleted.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task DeleteComputeNodeUserAsync( string userName, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.ProtocolLayer.DeleteComputeNodeUser(this.parentPoolId, this.Id, userName, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to delete the specified ComputeNodeUser. /// </summary> /// <param name="userName">The name of the ComputeNodeUser to be deleted.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void DeleteComputeNodeUser(string userName, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = DeleteComputeNodeUserAsync(userName, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Begins an asynchronous call to get RDP file data targeting the compute node of the current instance and write them to a specified Stream. /// </summary> /// <param name="rdpStream">The Stream into which the RDP file data will be written. This stream will not be closed or rewound by this call.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task GetRDPFileAsync(Stream rdpStream, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.ProtocolLayer.GetComputeNodeRDPFile(this.parentPoolId, this.Id, rdpStream, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to get RDP file data targeting the compute node of the current instance and write them to a specified Stream. /// </summary> /// <param name="rdpStream">The Stream into which the RDP file data will be written. This stream will not be closed or rewound by this call.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void GetRDPFile(Stream rdpStream, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = GetRDPFileAsync(rdpStream, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Begins an asynchronous call to get RDP file data targeting the compute node of the current instance and write them to a file with the specified name. /// </summary> /// <param name="rdpFileNameToCreate">The name of the RDP file to be created.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task GetRDPFileAsync( string rdpFileNameToCreate, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.PoolOperations.GetRDPFileViaFileNameAsyncImpl(this.parentPoolId, this.Id, rdpFileNameToCreate, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to get RDP file data targeting the compute node of the current instance and write them to a file with the specified name. /// </summary> /// <param name="rdpFileNameToCreate">The name of the RDP file to be created.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void GetRDPFile(string rdpFileNameToCreate, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = GetRDPFileAsync(rdpFileNameToCreate, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns> /// <remarks> /// <para>The get remote login settings operation runs asynchronously.</para> /// <para>This method can be invoked only if the pool is created with a <see cref="VirtualMachineConfiguration"/> property. /// If this method is invoked on pools created with <see cref="CloudServiceConfiguration" />, then Batch service returns 409 (Conflict). /// For pools with a <see cref="CloudServiceConfiguration" /> property, one of the GetRDPFileAsync/GetRDPFile methods must be used.</para> /// </remarks> public System.Threading.Tasks.Task<RemoteLoginSettings> GetRemoteLoginSettingsAsync(IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); System.Threading.Tasks.Task<RemoteLoginSettings> asyncTask = this.parentBatchClient.PoolOperations.GetRemoteLoginSettingsImpl( this.parentPoolId, this.Id, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Gets the settings required for remote login to a compute node. /// </summary> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <remarks> /// <para>This is a blocking operation. For a non-blocking equivalent, see <see cref="Microsoft.Azure.Batch.ComputeNode.GetRemoteLoginSettingsAsync"/>.</para> /// <para>This method can be invoked only if the pool is created with a <see cref="Microsoft.Azure.Batch.VirtualMachineConfiguration"/> property. /// If this method is invoked on pools created with <see cref="Microsoft.Azure.Batch.CloudServiceConfiguration" />, then Batch service returns 409 (Conflict). /// For pools with a <see cref="Microsoft.Azure.Batch.CloudServiceConfiguration" /> property, one of the GetRDPFileAsync/GetRDPFile methods must be used.</para> /// </remarks> public RemoteLoginSettings GetRemoteLoginSettings(IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task<RemoteLoginSettings> asyncTask = GetRemoteLoginSettingsAsync(additionalBehaviors); RemoteLoginSettings rls = asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); return rls; } /// <summary> /// Begins an asynchronous call to remove the compute node from the pool. /// </summary> /// <param name="deallocationOption"> /// Specifies how to handle tasks already running, and when the nodes running them may be removed from the pool. The default is <see cref="Common.ComputeNodeDeallocationOption.Requeue"/>. /// </param> /// <param name="resizeTimeout">The maximum amount of time which the RemoveFromPool operation can take before being terminated by the Azure Batch system.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task RemoveFromPoolAsync( Common.ComputeNodeDeallocationOption? deallocationOption = null, TimeSpan? resizeTimeout = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); List<string> computeNodeIds = new List<string> {this.Id}; Task asyncTask = this.parentBatchClient.PoolOperations.RemoveFromPoolAsyncImpl(this.parentPoolId, computeNodeIds, deallocationOption, resizeTimeout, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to remove the compute node from the pool. /// </summary> /// <param name="deallocationOption"> /// Specifies how to handle tasks already running, and when the nodes running them may be removed from the pool. The default is <see cref="Common.ComputeNodeDeallocationOption.Requeue"/>. /// </param> /// <param name="resizeTimeout">The maximum amount of time which the RemoveFromPool operation can take before being terminated by the Azure Batch system.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void RemoveFromPool(Common.ComputeNodeDeallocationOption? deallocationOption = null, TimeSpan? resizeTimeout = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = RemoveFromPoolAsync(deallocationOption, resizeTimeout, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Begins an asynchronous call to reboot the compute node. /// </summary> /// <param name="rebootOption">The reboot option associated with the reboot.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task RebootAsync( Common.ComputeNodeRebootOption? rebootOption = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.ProtocolLayer.RebootComputeNode(this.parentPoolId, this.Id, rebootOption, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to reboot the compute node. /// </summary> /// <param name="rebootOption">The reboot option associated with the reboot.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void Reboot(Common.ComputeNodeRebootOption? rebootOption = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = RebootAsync(rebootOption, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Begins an asynchronous call to reimage the compute node. /// </summary> /// <param name="reimageOption">The reimage option associated with the reimage.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task ReimageAsync( Common.ComputeNodeReimageOption? reimageOption = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.ProtocolLayer.ReimageComputeNode(this.parentPoolId, this.Id, reimageOption, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to reimage the compute node. /// </summary> /// <param name="reimageOption">The reimage option associated with the reimage.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> public void Reimage(Common.ComputeNodeReimageOption? reimageOption = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = ReimageAsync(reimageOption, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Begins an asynchronous request to get the specified NodeFile. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public System.Threading.Tasks.Task<NodeFile> GetNodeFileAsync( string filePath, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task<NodeFile> asyncTask = this.parentBatchClient.PoolOperations.GetNodeFileAsyncImpl(this.parentPoolId, this.Id, filePath, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Blocking call to get the specified NodeFile. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <returns>A bound <see cref="NodeFile"/> object.</returns> public NodeFile GetNodeFile(string filePath, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task<NodeFile> asyncTask = this.GetNodeFileAsync(filePath, additionalBehaviors); return asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Copies the contents of a file from the node to the given <see cref="Stream"/>. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="stream">The stream to copy the file contents to.</param> /// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task CopyNodeFileContentToStreamAsync( string filePath, Stream stream, GetFileRequestByteRange byteRange = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); Task asyncTask = this.parentBatchClient.PoolOperations.CopyNodeFileContentToStreamAsyncImpl( this.parentPoolId, this.Id, filePath, stream, byteRange, bhMgr, cancellationToken); return asyncTask; } /// <summary> /// Copies the contents of a file from the node to the given <see cref="Stream"/>. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="stream">The stream to copy the file contents to.</param> /// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <returns>A bound <see cref="NodeFile"/> object.</returns> public void CopyNodeFileContentToStream( string filePath, Stream stream, GetFileRequestByteRange byteRange = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = this.CopyNodeFileContentToStreamAsync(filePath, stream, byteRange, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Reads the contents of a file from the specified node into a string. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="encoding">The encoding to use. If no value or null is specified, UTF8 is used.</param> /// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> object that represents the asynchronous operation.</returns> public Task<string> CopyNodeFileContentToStringAsync( string filePath, Encoding encoding = null, GetFileRequestByteRange byteRange = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); return this.parentBatchClient.PoolOperations.CopyNodeFileContentToStringAsyncImpl( this.parentPoolId, this.Id, filePath, encoding, byteRange, bhMgr, cancellationToken); } /// <summary> /// Reads the contents of a file from the specified node into a string. /// </summary> /// <param name="filePath">The path of the file to retrieve.</param> /// <param name="encoding">The encoding to use. If no value or null is specified, UTF8 is used.</param> /// <param name="byteRange">A byte range defining what section of the file to copy. If omitted, the entire file is downloaded.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object.</param> /// <returns>A bound <see cref="NodeFile"/> object.</returns> public string CopyNodeFileContentToString( string filePath, Encoding encoding = null, GetFileRequestByteRange byteRange = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task<string> asyncTask = this.CopyNodeFileContentToStringAsync(filePath, encoding, byteRange, additionalBehaviors); return asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Exposes synchronous and asynchronous enumeration of the files for the node. /// </summary> /// <param name="recursive">If true, performs a recursive list of all files of the node. If false, returns only the files at the node directory root.</param> /// <param name="detailLevel">Controls the detail level of the data returned by a call to the Azure Batch Service.</param> /// <param name="additionalBehaviors">A collection of BatchClientBehavior instances that are applied after the CustomBehaviors on the current object and after the behavior implementing the DetailLevel.</param> /// <returns>An instance of IPagedEnumerable that can be used to enumerate objects using either synchronous or asynchronous patterns.</returns> public IPagedEnumerable<NodeFile> ListNodeFiles(bool? recursive = null, DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { // craft the behavior manager for this call BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); IPagedEnumerable<NodeFile> enumerator = this.parentBatchClient.PoolOperations.ListNodeFilesImpl(this.parentPoolId, this.Id, recursive, bhMgr, detailLevel); return enumerator; } /// <summary> /// Enables task scheduling on the compute node. /// </summary> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns> /// <remarks>This operation runs asynchronously.</remarks> public System.Threading.Tasks.Task EnableSchedulingAsync( IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { System.Threading.Tasks.Task asyncTask = this.parentBatchClient.PoolOperations.EnableComputeNodeSchedulingAsync(this.parentPoolId, this.Id, additionalBehaviors, cancellationToken); return asyncTask; } /// <summary> /// Enables task scheduling on the compute node. /// </summary> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="EnableScheduling"/>.</remarks> public void EnableScheduling(IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = EnableSchedulingAsync(additionalBehaviors, CancellationToken.None); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Disables task scheduling on the compute node. /// </summary> /// <param name="disableComputeNodeSchedulingOption">Specifies what to do with currently running tasks. The default is <see cref="Common.DisableComputeNodeSchedulingOption.Requeue"/>.</param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns> /// <remarks>This operation runs asynchronously.</remarks> public System.Threading.Tasks.Task DisableSchedulingAsync( Common.DisableComputeNodeSchedulingOption? disableComputeNodeSchedulingOption, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { System.Threading.Tasks.Task asyncTask = this.parentBatchClient.PoolOperations.DisableComputeNodeSchedulingAsync(this.parentPoolId, this.Id, disableComputeNodeSchedulingOption, additionalBehaviors, cancellationToken); return asyncTask; } /// <summary> /// Disables task scheduling on the compute node. /// </summary> /// <param name="disableComputeNodeSchedulingOption">Specifies what to do with currently running tasks. The default is <see cref="Common.DisableComputeNodeSchedulingOption.Requeue"/>.</param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <remarks>This is a blocking operation. For a non-blocking equivalent, see <see cref="DisableSchedulingAsync"/>.</remarks> public void DisableScheduling( Common.DisableComputeNodeSchedulingOption? disableComputeNodeSchedulingOption, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = DisableSchedulingAsync(disableComputeNodeSchedulingOption, additionalBehaviors, CancellationToken.None); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Upload Azure Batch service log files from the compute node. /// </summary> /// <param name="containerUrl"> /// The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). The URL must include a Shared Access Signature (SAS) granting write permissions to the container. /// </param> /// <param name="startTime"> /// The start of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. /// </param> /// <param name="endTime"> /// The end of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. If this is omitted, the default is the current time. /// </param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns> /// <remarks> /// This is for gathering Azure Batch service log files in an automated fashion from nodes if you are experiencing an error and wish to escalate to Azure support. /// The Azure Batch service log files should be shared with Azure support to aid in debugging issues with the Batch service. /// </remarks> public System.Threading.Tasks.Task<UploadBatchServiceLogsResult> UploadComputeNodeBatchServiceLogsAsync( string containerUrl, DateTime startTime, DateTime? endTime = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // craft the behavior manager for this call BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); return this.parentBatchClient.PoolOperations.UploadComputeNodeBatchServiceLogsAsyncImpl( this.parentPoolId, this.Id, containerUrl, startTime, endTime, null, bhMgr, cancellationToken); } /// <summary> /// Upload Azure Batch service log files from the compute node. /// </summary> /// <param name="containerUrl"> /// The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). The URL must include a Shared Access Signature (SAS) granting write permissions to the container. /// </param> /// <param name="identityReference">A managed identity to use for writing to the container.</param> /// <param name="startTime"> /// The start of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. /// </param> /// <param name="endTime"> /// The end of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. If this is omitted, the default is the current time. /// </param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="System.Threading.Tasks.Task"/> that represents the asynchronous operation.</returns> /// <remarks> /// This is for gathering Azure Batch service log files in an automated fashion from nodes if you are experiencing an error and wish to escalate to Azure support. /// The Azure Batch service log files should be shared with Azure support to aid in debugging issues with the Batch service. /// </remarks> public System.Threading.Tasks.Task<UploadBatchServiceLogsResult> UploadComputeNodeBatchServiceLogsAsync( string containerUrl, ComputeNodeIdentityReference identityReference, DateTime startTime, DateTime? endTime = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // craft the behavior manager for this call BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors); return this.parentBatchClient.PoolOperations.UploadComputeNodeBatchServiceLogsAsyncImpl( this.parentPoolId, this.Id, containerUrl, startTime, endTime, identityReference, bhMgr, cancellationToken); } /// <summary> /// Upload Azure Batch service log files from the specified compute node. /// </summary> /// <param name="containerUrl"> /// The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). The URL must include a Shared Access Signature (SAS) granting write permissions to the container. /// </param> /// <param name="startTime"> /// The start of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. /// </param> /// <param name="endTime"> /// The end of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. If this is omitted, the default is the current time. /// </param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <remarks> /// This is for gathering Azure Batch service log files in an automated fashion from nodes if you are experiencing an error and wish to escalate to Azure support. /// The Azure Batch service log files should be shared with Azure support to aid in debugging issues with the Batch service. /// </remarks> /// <returns>The result of uploading the batch service logs.</returns> public UploadBatchServiceLogsResult UploadComputeNodeBatchServiceLogs( string containerUrl, DateTime startTime, DateTime? endTime = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { var asyncTask = this.UploadComputeNodeBatchServiceLogsAsync( containerUrl, startTime, endTime, additionalBehaviors); return asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } /// <summary> /// Upload Azure Batch service log files from the specified compute node. /// </summary> /// <param name="containerUrl"> /// The URL of the container within Azure Blob Storage to which to upload the Batch Service log file(s). The URL must include a Shared Access Signature (SAS) granting write permissions to the container. /// </param> /// <param name="identityReference">A managed identity to use for writing to the container.</param> /// <param name="startTime"> /// The start of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. /// </param> /// <param name="endTime"> /// The end of the time range from which to upload Batch Service log file(s). Any log file containing a log message in the time range will be uploaded. /// This means that the operation might retrieve more logs than have been requested since the entire log file is always uploaded. If this is omitted, the default is the current time. /// </param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <remarks> /// This is for gathering Azure Batch service log files in an automated fashion from nodes if you are experiencing an error and wish to escalate to Azure support. /// The Azure Batch service log files should be shared with Azure support to aid in debugging issues with the Batch service. /// </remarks> /// <returns>The result of uploading the batch service logs.</returns> public UploadBatchServiceLogsResult UploadComputeNodeBatchServiceLogs( string containerUrl, ComputeNodeIdentityReference identityReference, DateTime startTime, DateTime? endTime = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { var asyncTask = this.UploadComputeNodeBatchServiceLogsAsync( containerUrl, identityReference, startTime, endTime, additionalBehaviors); return asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } #endregion ComputeNode #region IRefreshable /// <summary> /// Refreshes the current <see cref="ComputeNode"/>. /// </summary> /// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> /// <param name="cancellationToken">A <see cref="CancellationToken"/> for controlling the lifetime of the asynchronous operation.</param> /// <returns>A <see cref="Task"/> representing the asynchronous refresh operation.</returns> public async Task RefreshAsync(DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null, CancellationToken cancellationToken = default(CancellationToken)) { // create the behavior manager BehaviorManager bhMgr = new BehaviorManager(this.CustomBehaviors, additionalBehaviors, detailLevel); System.Threading.Tasks.Task<AzureOperationResponse<Models.ComputeNode, Models.ComputeNodeGetHeaders>> asyncTask = this.parentBatchClient.ProtocolLayer.GetComputeNode(this.parentPoolId, this.Id, bhMgr, cancellationToken); AzureOperationResponse<Models.ComputeNode, Models.ComputeNodeGetHeaders> response = await asyncTask.ConfigureAwait(continueOnCapturedContext: false); // get pool from response Models.ComputeNode newProtocolComputeNode = response.Body; this.propertyContainer = new PropertyContainer(newProtocolComputeNode); } /// <summary> /// Refreshes the <see cref="ComputeNode"/>. /// </summary> /// <param name="detailLevel">The detail level for the refresh. If a detail level which omits the <see cref="Id"/> property is specified, refresh will fail.</param> /// <param name="additionalBehaviors">A collection of <see cref="BatchClientBehavior"/> instances that are applied to the Batch service request after the <see cref="CustomBehaviors"/>.</param> public void Refresh(DetailLevel detailLevel = null, IEnumerable<BatchClientBehavior> additionalBehaviors = null) { Task asyncTask = RefreshAsync(detailLevel, additionalBehaviors); asyncTask.WaitAndUnaggregateException(this.CustomBehaviors, additionalBehaviors); } #endregion } }
using System; using Microsoft.Xna.Framework; using CocosSharp; namespace GameStarterKit { public class GameMenu : CCLayer { CCMenu VoiceFXMenu; CCMenu SoundFXMenu; CCMenu AmbientFXMenu; CCPoint VoiceFXMenuLocation; CCPoint SoundFXMenuLocation; CCPoint AmbientFXMenuLocation; string voiceButtonName; string voiceButtonNameDim; string soundButtonName; string soundButtonNameDim; string ambientButtonName; string ambientButtonNameDim; public GameMenu() { var screenSize = Director.WindowSizeInPixels; voiceButtonName = "VoiceFX"; voiceButtonNameDim = "VoiceFX"; soundButtonName = "SoundFX"; soundButtonNameDim = "SoundFX"; ambientButtonName = "AmbientFX"; ambientButtonNameDim = "AmbientFX"; SoundFXMenuLocation = new CCPoint(110, 55); VoiceFXMenuLocation = new CCPoint(230, 55); AmbientFXMenuLocation = new CCPoint(355, 55); // TouchEnabled = true; IsSoundFXMenuItemActive = !GameData.SharedData.AreSoundFXMuted; IsVoiceFXMenuActive = !GameData.SharedData.AreVoiceFXMuted; IsAmbientFXMenuActive = !GameData.SharedData.AreAmbientFXMuted; } void PlayNegativeSound(object sender) { //play a sound indicating this level isn't available } public static CCScene Scene { get { // 'scene' is an autorelease object. CCScene scene = new CCScene(); // 'layer' is an autorelease object. GameMenu layer = new GameMenu(); // add layer as a child to scene scene.AddChild(layer); // return the scene return scene; } } #region SECTION BUTTONS #region POP (remove) SCENE and Transition to new level void PopAndTransition() { Director.PopScene(); //when TheLevel scene reloads it will start with a new level GameLevel.SharedLevel.TransitionAfterMenuPop(); } #endregion #region POP (remove) SCENE and continue playing current level //public override void TouchesBegan(System.Collections.Generic.List<CCTouch> touches, CCEvent event_) //{ // CCDirector.SharedDirector.PopScene(); //} #endregion #region VOICE FX bool IsVoiceFXMenuActive { set { RemoveChild(VoiceFXMenu, true); CCMenuItem button1; CCLabel label; if (!value) { label = new CCLabel(voiceButtonNameDim, "MarkerFelt", 18); label.Color = CCColor3B.Gray; button1 = new CCMenuItemLabel(label, TurnVoiceFXOn); } else { label = new CCLabel(voiceButtonName, "MarkerFelt", 18); label.Color = CCColor3B.Yellow; button1 = new CCMenuItemLabel(label, TurnVoiceFXOff); } VoiceFXMenu = new CCMenu(button1); VoiceFXMenu.Position = VoiceFXMenuLocation; AddChild(VoiceFXMenu, 10); } } void TurnVoiceFXOn(object sender) { GameData.SharedData.AreVoiceFXMuted = false; IsVoiceFXMenuActive = true; } void TurnVoiceFXOff(object sender) { GameData.SharedData.AreVoiceFXMuted = true; IsVoiceFXMenuActive = false; } #endregion #region Sound FX bool IsSoundFXMenuItemActive { set { RemoveChild(SoundFXMenu, true); CCMenuItemLabel button1; CCLabel label; if (!value) { label = new CCLabel(soundButtonNameDim, "MarkerFelt", 18); label.Color = CCColor3B.Gray; button1 = new CCMenuItemLabel(label, TurnSoundFXOn); } else { label = new CCLabel(soundButtonName, "MarkerFelt", 18); label.Color = CCColor3B.Yellow; button1 = new CCMenuItemLabel(label, TurnSoundFXOff); } SoundFXMenu = new CCMenu(button1); SoundFXMenu.Position = SoundFXMenuLocation; AddChild(SoundFXMenu, 10); } } void TurnSoundFXOn(object sender) { GameData.SharedData.AreSoundFXMuted = false; IsSoundFXMenuItemActive = true; } void TurnSoundFXOff(object sender) { GameData.SharedData.AreSoundFXMuted = true; IsSoundFXMenuItemActive = false; } #endregion #region Ambient FX bool IsAmbientFXMenuActive { set { RemoveChild(AmbientFXMenu, true); CCMenuItemLabel button1; CCLabel label; if (!value) { label = new CCLabel(ambientButtonName, "MarkerFelt", 18); label.Color = CCColor3B.Gray; button1 = new CCMenuItemLabel(label, TurnAmbientFXOn); } else { label = new CCLabel(ambientButtonNameDim, "MarkerFelt", 18); label.Color = CCColor3B.Yellow; button1 = new CCMenuItemLabel(label, TurnAmbientFXOff); } AmbientFXMenu = new CCMenu(button1); AmbientFXMenu.Position = AmbientFXMenuLocation; AddChild(AmbientFXMenu, 10); } } void TurnAmbientFXOn(object sender) { GameData.SharedData.AreAmbientFXMuted = true; IsAmbientFXMenuActive = true; } void TurnAmbientFXOff(object sender) { GameData.SharedData.AreAmbientFXMuted = false; IsAmbientFXMenuActive = false; } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.DirectoryServices.Interop; namespace System.DirectoryServices { /// <devdoc> /// Holds a collection of values for a multi-valued property. /// </devdoc> public class PropertyValueCollection : CollectionBase { internal enum UpdateType { Add = 0, Delete = 1, Update = 2, None = 3 } private readonly DirectoryEntry _entry; private UpdateType _updateType = UpdateType.None; private readonly ArrayList _changeList = null; private readonly bool _allowMultipleChange = false; private readonly bool _needNewBehavior = false; internal PropertyValueCollection(DirectoryEntry entry, string propertyName) { _entry = entry; PropertyName = propertyName; PopulateList(); ArrayList tempList = new ArrayList(); _changeList = ArrayList.Synchronized(tempList); _allowMultipleChange = entry.allowMultipleChange; string tempPath = entry.Path; if (tempPath == null || tempPath.Length == 0) { // user does not specify path, so we bind to default naming context using LDAP provider. _needNewBehavior = true; } else { if (tempPath.StartsWith("LDAP:", StringComparison.Ordinal)) _needNewBehavior = true; } } public object this[int index] { get => List[index]; set { if (_needNewBehavior && !_allowMultipleChange) throw new NotSupportedException(); else { List[index] = value; } } } public string PropertyName { get; } public object Value { get { if (this.Count == 0) return null; else if (this.Count == 1) return List[0]; else { object[] objectArray = new object[this.Count]; List.CopyTo(objectArray, 0); return objectArray; } } set { try { this.Clear(); } catch (System.Runtime.InteropServices.COMException e) { if (e.ErrorCode != unchecked((int)0x80004005) || (value == null)) // WinNT provider throws E_FAIL when null value is specified though actually ADS_PROPERTY_CLEAR option is used, need to catch exception // here. But at the same time we don't want to catch the exception if user explicitly sets the value to null. throw; } if (value == null) return; // we could not do Clear and Add, we have to bypass the existing collection cache _changeList.Clear(); if (value is Array) { // byte[] is a special case, we will follow what ADSI is doing, it must be an octet string. So treat it as a single valued attribute if (value is byte[]) _changeList.Add(value); else if (value is object[]) _changeList.AddRange((object[])value); else { //Need to box value type array elements. object[] objArray = new object[((Array)value).Length]; ((Array)value).CopyTo(objArray, 0); _changeList.AddRange((object[])objArray); } } else _changeList.Add(value); object[] allValues = new object[_changeList.Count]; _changeList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues); _entry.CommitIfNotCaching(); // populate the new context PopulateList(); } } /// <devdoc> /// Appends the value to the set of values for this property. /// </devdoc> public int Add(object value) => List.Add(value); /// <devdoc> /// Appends the values to the set of values for this property. /// </devdoc> public void AddRange(object[] value) { if (value == null) { throw new ArgumentNullException("value"); } for (int i = 0; ((i) < (value.Length)); i = ((i) + (1))) { this.Add(value[i]); } } /// <devdoc> /// Appends the values to the set of values for this property. /// </devdoc> public void AddRange(PropertyValueCollection value) { if (value == null) { throw new ArgumentNullException("value"); } int currentCount = value.Count; for (int i = 0; i < currentCount; i = ((i) + (1))) { this.Add(value[i]); } } public bool Contains(object value) => List.Contains(value); /// <devdoc> /// Copies the elements of this instance into an <see cref='System.Array'/>, /// starting at a particular index into the given <paramref name="array"/>. /// </devdoc> public void CopyTo(object[] array, int index) { List.CopyTo(array, index); } public int IndexOf(object value) => List.IndexOf(value); public void Insert(int index, object value) => List.Insert(index, value); private void PopulateList() { //No need to fill the cache here, when GetEx is calles, an implicit //call to GetInfo will be called against an uninitialized property //cache. Which is exactly what FillCache does. //entry.FillCache(propertyName); object var; int unmanagedResult = _entry.AdsObject.GetEx(PropertyName, out var); if (unmanagedResult != 0) { // property not found (IIS provider returns 0x80005006, other provides return 0x8000500D). if ((unmanagedResult == unchecked((int)0x8000500D)) || (unmanagedResult == unchecked((int)0x80005006))) { return; } else { throw COMExceptionHelper.CreateFormattedComException(unmanagedResult); } } if (var is ICollection) InnerList.AddRange((ICollection)var); else InnerList.Add(var); } /// <devdoc> /// Removes the value from the collection. /// </devdoc> public void Remove(object value) { if (_needNewBehavior) { try { List.Remove(value); } catch (ArgumentException) { // exception is thrown because value does not exist in the current cache, but it actually might do exist just because it is a very // large multivalued attribute, the value has not been downloaded yet. OnRemoveComplete(0, value); } } else List.Remove(value); } protected override void OnClearComplete() { if (_needNewBehavior && !_allowMultipleChange && _updateType != UpdateType.None && _updateType != UpdateType.Update) { throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation); } _entry.AdsObject.PutEx((int)AdsPropertyOperation.Clear, PropertyName, null); _updateType = UpdateType.Update; try { _entry.CommitIfNotCaching(); } catch (System.Runtime.InteropServices.COMException e) { // On ADSI 2.5 if property has not been assigned any value before, // then IAds::SetInfo() in CommitIfNotCaching returns bad HREsult 0x8007200A, which we ignore. if (e.ErrorCode != unchecked((int)0x8007200A)) // ERROR_DS_NO_ATTRIBUTE_OR_VALUE throw; } } protected override void OnInsertComplete(int index, object value) { if (_needNewBehavior) { if (!_allowMultipleChange) { if (_updateType != UpdateType.None && _updateType != UpdateType.Add) { throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation); } _changeList.Add(value); object[] allValues = new object[_changeList.Count]; _changeList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, allValues); _updateType = UpdateType.Add; } else { _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { value }); } } else { object[] allValues = new object[InnerList.Count]; InnerList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues); } _entry.CommitIfNotCaching(); } protected override void OnRemoveComplete(int index, object value) { if (_needNewBehavior) { if (!_allowMultipleChange) { if (_updateType != UpdateType.None && _updateType != UpdateType.Delete) { throw new InvalidOperationException(SR.DSPropertyValueSupportOneOperation); } _changeList.Add(value); object[] allValues = new object[_changeList.Count]; _changeList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, allValues); _updateType = UpdateType.Delete; } else { _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { value }); } } else { object[] allValues = new object[InnerList.Count]; InnerList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues); } _entry.CommitIfNotCaching(); } protected override void OnSetComplete(int index, object oldValue, object newValue) { // no need to consider the not allowing accumulative change case as it does not support Set if (Count <= 1) { _entry.AdsObject.Put(PropertyName, newValue); } else { if (_needNewBehavior) { _entry.AdsObject.PutEx((int)AdsPropertyOperation.Delete, PropertyName, new object[] { oldValue }); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Append, PropertyName, new object[] { newValue }); } else { object[] allValues = new object[InnerList.Count]; InnerList.CopyTo(allValues, 0); _entry.AdsObject.PutEx((int)AdsPropertyOperation.Update, PropertyName, allValues); } } _entry.CommitIfNotCaching(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using System.Text.RegularExpressions; namespace BizTalk.MapperExtensions.Functoid.Wizard { public class WzPageResourceSetup : Microsoft.BizTalk.Wizard.WizardInteriorPage, WizardControlInterface { #region Global Variables private const string IdRegEx= @"^0*([7-9]\d{3,}|[1-6]\d{4,}|600[1-9]|60[1-9]\d|6[1-9]\d{2})$"; public event AddWizardResultEvent _AddWizardResultEvent; #endregion #region Form Components private System.ComponentModel.IContainer components = null; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.OpenFileDialog openFileDialog; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox txtId; private System.Windows.Forms.TextBox txtName; private System.Windows.Forms.TextBox txtTooltip; private System.Windows.Forms.TextBox txtDescription; private System.Windows.Forms.ErrorProvider errorProvider; #endregion public WzPageResourceSetup() { // This call is required by the Windows Form Designer. InitializeComponent(); this.AutoScaleDimensions = new SizeF(6F, 13F); this.AutoScaleMode = AutoScaleMode.Font; // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } public bool NextButtonEnabled { get { return GetAllStates(); } } public bool NeedSummary { get { return false; } } protected void AddWizardResult(string strName, object Value) { PropertyPairEvent PropertyPair = new PropertyPairEvent(strName, Value); OnAddWizardResult(PropertyPair); } /// <summary> /// The protected OnRaiseProperty method raises the event by invoking /// the delegates. The sender is always this, the current instance /// of the class. /// </summary> /// <param name="e"></param> protected virtual void OnAddWizardResult(PropertyPairEvent e) { if (e != null) { // Invokes the delegates. _AddWizardResultEvent(this,e); } } private void WzPageResourceSetup_Leave(object sender, System.EventArgs e) { try { // Save wizard results AddWizardResult(WizardValues.FunctoidID, txtId.Text); AddWizardResult(WizardValues.FunctoidName, txtName.Text); AddWizardResult(WizardValues.FunctoidToolTip, txtTooltip.Text); AddWizardResult(WizardValues.FunctoidDescription, txtDescription.Text); } catch(Exception err) { MessageBox.Show(err.Message); Trace.WriteLine(err.Message + Environment.NewLine + err.StackTrace); } } /// <summary> /// Resets all of the errorproviders when anything succeeds /// </summary> private void ResetAllErrProviders() { foreach(Control ctl in this.Controls) { errorProvider.SetError(ctl, ""); } } private void Element_Changed(object sender, System.EventArgs e) { EnableNext(GetAllStates()); } private bool GetAllStates() { return (Regex.IsMatch(txtId.Text, IdRegEx) && txtName.Text.Trim().Length > 0); } private void txtId_Validating(object sender, System.ComponentModel.CancelEventArgs e) { // Validate Id if (txtId.Text.Trim() == "") errorProvider.SetError(txtId, "Id cannot be empty"); else if (!Regex.IsMatch(txtId.Text,IdRegEx)) errorProvider.SetError(txtId, "Id must be a number > 6000"); else errorProvider.SetError(txtId, ""); // Enable Next if everything's OK EnableNext(GetAllStates()); } private void txtName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { // Validate Name if (txtName.Text.Trim() == "") errorProvider.SetError(txtName, "Name cannot be empty"); else errorProvider.SetError(txtName, ""); // Enable Next if everything's OK EnableNext(GetAllStates()); } #region 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.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(WzPageResourceSetup)); this.txtId = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.errorProvider = new System.Windows.Forms.ErrorProvider(); this.txtName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.txtTooltip = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.txtDescription = new System.Windows.Forms.TextBox(); this.openFileDialog = new System.Windows.Forms.OpenFileDialog(); this.panelHeader.SuspendLayout(); this.SuspendLayout(); // // panelHeader // this.panelHeader.Name = "panelHeader"; this.panelHeader.Size = ((System.Drawing.Size)(resources.GetObject("panelHeader.Size"))); // // labelTitle // this.labelTitle.Name = "labelTitle"; this.labelTitle.Size = ((System.Drawing.Size)(resources.GetObject("labelTitle.Size"))); this.labelTitle.Text = resources.GetString("labelTitle.Text"); // // labelSubTitle // this.labelSubTitle.Name = "labelSubTitle"; this.labelSubTitle.Size = ((System.Drawing.Size)(resources.GetObject("labelSubTitle.Size"))); this.labelSubTitle.Text = resources.GetString("labelSubTitle.Text"); // // txtId // this.txtId.AccessibleDescription = resources.GetString("txtId.AccessibleDescription"); this.txtId.AccessibleName = resources.GetString("txtId.AccessibleName"); this.txtId.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtId.Anchor"))); this.txtId.AutoSize = ((bool)(resources.GetObject("txtId.AutoSize"))); this.txtId.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtId.BackgroundImage"))); this.txtId.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtId.Dock"))); this.txtId.Enabled = ((bool)(resources.GetObject("txtId.Enabled"))); this.errorProvider.SetError(this.txtId, resources.GetString("txtId.Error")); this.txtId.Font = ((System.Drawing.Font)(resources.GetObject("txtId.Font"))); this.errorProvider.SetIconAlignment(this.txtId, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("txtId.IconAlignment")))); this.errorProvider.SetIconPadding(this.txtId, ((int)(resources.GetObject("txtId.IconPadding")))); this.txtId.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtId.ImeMode"))); this.txtId.Location = ((System.Drawing.Point)(resources.GetObject("txtId.Location"))); this.txtId.MaxLength = ((int)(resources.GetObject("txtId.MaxLength"))); this.txtId.Multiline = ((bool)(resources.GetObject("txtId.Multiline"))); this.txtId.Name = "txtId"; this.txtId.PasswordChar = ((char)(resources.GetObject("txtId.PasswordChar"))); this.txtId.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtId.RightToLeft"))); this.txtId.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtId.ScrollBars"))); this.txtId.Size = ((System.Drawing.Size)(resources.GetObject("txtId.Size"))); this.txtId.TabIndex = ((int)(resources.GetObject("txtId.TabIndex"))); this.txtId.Text = resources.GetString("txtId.Text"); this.txtId.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtId.TextAlign"))); this.txtId.Visible = ((bool)(resources.GetObject("txtId.Visible"))); this.txtId.WordWrap = ((bool)(resources.GetObject("txtId.WordWrap"))); this.txtId.Validating += new System.ComponentModel.CancelEventHandler(this.txtId_Validating); this.txtId.TextChanged += new System.EventHandler(this.Element_Changed); // // label2 // this.label2.AccessibleDescription = resources.GetString("label2.AccessibleDescription"); this.label2.AccessibleName = resources.GetString("label2.AccessibleName"); this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label2.Anchor"))); this.label2.AutoSize = ((bool)(resources.GetObject("label2.AutoSize"))); this.label2.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label2.Dock"))); this.label2.Enabled = ((bool)(resources.GetObject("label2.Enabled"))); this.errorProvider.SetError(this.label2, resources.GetString("label2.Error")); this.label2.Font = ((System.Drawing.Font)(resources.GetObject("label2.Font"))); this.errorProvider.SetIconAlignment(this.label2, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("label2.IconAlignment")))); this.errorProvider.SetIconPadding(this.label2, ((int)(resources.GetObject("label2.IconPadding")))); this.label2.Image = ((System.Drawing.Image)(resources.GetObject("label2.Image"))); this.label2.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label2.ImageAlign"))); this.label2.ImageIndex = ((int)(resources.GetObject("label2.ImageIndex"))); this.label2.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label2.ImeMode"))); this.label2.Location = ((System.Drawing.Point)(resources.GetObject("label2.Location"))); this.label2.Name = "label2"; this.label2.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label2.RightToLeft"))); this.label2.Size = ((System.Drawing.Size)(resources.GetObject("label2.Size"))); this.label2.TabIndex = ((int)(resources.GetObject("label2.TabIndex"))); this.label2.Text = resources.GetString("label2.Text"); this.label2.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label2.TextAlign"))); this.label2.Visible = ((bool)(resources.GetObject("label2.Visible"))); // // errorProvider // this.errorProvider.ContainerControl = this; this.errorProvider.Icon = ((System.Drawing.Icon)(resources.GetObject("errorProvider.Icon"))); // // txtName // this.txtName.AccessibleDescription = resources.GetString("txtName.AccessibleDescription"); this.txtName.AccessibleName = resources.GetString("txtName.AccessibleName"); this.txtName.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtName.Anchor"))); this.txtName.AutoSize = ((bool)(resources.GetObject("txtName.AutoSize"))); this.txtName.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtName.BackgroundImage"))); this.txtName.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtName.Dock"))); this.txtName.Enabled = ((bool)(resources.GetObject("txtName.Enabled"))); this.errorProvider.SetError(this.txtName, resources.GetString("txtName.Error")); this.txtName.Font = ((System.Drawing.Font)(resources.GetObject("txtName.Font"))); this.errorProvider.SetIconAlignment(this.txtName, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("txtName.IconAlignment")))); this.errorProvider.SetIconPadding(this.txtName, ((int)(resources.GetObject("txtName.IconPadding")))); this.txtName.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtName.ImeMode"))); this.txtName.Location = ((System.Drawing.Point)(resources.GetObject("txtName.Location"))); this.txtName.MaxLength = ((int)(resources.GetObject("txtName.MaxLength"))); this.txtName.Multiline = ((bool)(resources.GetObject("txtName.Multiline"))); this.txtName.Name = "txtName"; this.txtName.PasswordChar = ((char)(resources.GetObject("txtName.PasswordChar"))); this.txtName.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtName.RightToLeft"))); this.txtName.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtName.ScrollBars"))); this.txtName.Size = ((System.Drawing.Size)(resources.GetObject("txtName.Size"))); this.txtName.TabIndex = ((int)(resources.GetObject("txtName.TabIndex"))); this.txtName.Text = resources.GetString("txtName.Text"); this.txtName.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtName.TextAlign"))); this.txtName.Visible = ((bool)(resources.GetObject("txtName.Visible"))); this.txtName.WordWrap = ((bool)(resources.GetObject("txtName.WordWrap"))); this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtName_Validating); this.txtName.TextChanged += new System.EventHandler(this.Element_Changed); // // label1 // this.label1.AccessibleDescription = resources.GetString("label1.AccessibleDescription"); this.label1.AccessibleName = resources.GetString("label1.AccessibleName"); this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label1.Anchor"))); this.label1.AutoSize = ((bool)(resources.GetObject("label1.AutoSize"))); this.label1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label1.Dock"))); this.label1.Enabled = ((bool)(resources.GetObject("label1.Enabled"))); this.errorProvider.SetError(this.label1, resources.GetString("label1.Error")); this.label1.Font = ((System.Drawing.Font)(resources.GetObject("label1.Font"))); this.errorProvider.SetIconAlignment(this.label1, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("label1.IconAlignment")))); this.errorProvider.SetIconPadding(this.label1, ((int)(resources.GetObject("label1.IconPadding")))); this.label1.Image = ((System.Drawing.Image)(resources.GetObject("label1.Image"))); this.label1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label1.ImageAlign"))); this.label1.ImageIndex = ((int)(resources.GetObject("label1.ImageIndex"))); this.label1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label1.ImeMode"))); this.label1.Location = ((System.Drawing.Point)(resources.GetObject("label1.Location"))); this.label1.Name = "label1"; this.label1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label1.RightToLeft"))); this.label1.Size = ((System.Drawing.Size)(resources.GetObject("label1.Size"))); this.label1.TabIndex = ((int)(resources.GetObject("label1.TabIndex"))); this.label1.Text = resources.GetString("label1.Text"); this.label1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label1.TextAlign"))); this.label1.Visible = ((bool)(resources.GetObject("label1.Visible"))); // // label3 // this.label3.AccessibleDescription = resources.GetString("label3.AccessibleDescription"); this.label3.AccessibleName = resources.GetString("label3.AccessibleName"); this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label3.Anchor"))); this.label3.AutoSize = ((bool)(resources.GetObject("label3.AutoSize"))); this.label3.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label3.Dock"))); this.label3.Enabled = ((bool)(resources.GetObject("label3.Enabled"))); this.errorProvider.SetError(this.label3, resources.GetString("label3.Error")); this.label3.Font = ((System.Drawing.Font)(resources.GetObject("label3.Font"))); this.errorProvider.SetIconAlignment(this.label3, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("label3.IconAlignment")))); this.errorProvider.SetIconPadding(this.label3, ((int)(resources.GetObject("label3.IconPadding")))); this.label3.Image = ((System.Drawing.Image)(resources.GetObject("label3.Image"))); this.label3.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label3.ImageAlign"))); this.label3.ImageIndex = ((int)(resources.GetObject("label3.ImageIndex"))); this.label3.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label3.ImeMode"))); this.label3.Location = ((System.Drawing.Point)(resources.GetObject("label3.Location"))); this.label3.Name = "label3"; this.label3.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label3.RightToLeft"))); this.label3.Size = ((System.Drawing.Size)(resources.GetObject("label3.Size"))); this.label3.TabIndex = ((int)(resources.GetObject("label3.TabIndex"))); this.label3.Text = resources.GetString("label3.Text"); this.label3.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label3.TextAlign"))); this.label3.Visible = ((bool)(resources.GetObject("label3.Visible"))); // // txtTooltip // this.txtTooltip.AccessibleDescription = resources.GetString("txtTooltip.AccessibleDescription"); this.txtTooltip.AccessibleName = resources.GetString("txtTooltip.AccessibleName"); this.txtTooltip.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtTooltip.Anchor"))); this.txtTooltip.AutoSize = ((bool)(resources.GetObject("txtTooltip.AutoSize"))); this.txtTooltip.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtTooltip.BackgroundImage"))); this.txtTooltip.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtTooltip.Dock"))); this.txtTooltip.Enabled = ((bool)(resources.GetObject("txtTooltip.Enabled"))); this.errorProvider.SetError(this.txtTooltip, resources.GetString("txtTooltip.Error")); this.txtTooltip.Font = ((System.Drawing.Font)(resources.GetObject("txtTooltip.Font"))); this.errorProvider.SetIconAlignment(this.txtTooltip, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("txtTooltip.IconAlignment")))); this.errorProvider.SetIconPadding(this.txtTooltip, ((int)(resources.GetObject("txtTooltip.IconPadding")))); this.txtTooltip.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtTooltip.ImeMode"))); this.txtTooltip.Location = ((System.Drawing.Point)(resources.GetObject("txtTooltip.Location"))); this.txtTooltip.MaxLength = ((int)(resources.GetObject("txtTooltip.MaxLength"))); this.txtTooltip.Multiline = ((bool)(resources.GetObject("txtTooltip.Multiline"))); this.txtTooltip.Name = "txtTooltip"; this.txtTooltip.PasswordChar = ((char)(resources.GetObject("txtTooltip.PasswordChar"))); this.txtTooltip.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtTooltip.RightToLeft"))); this.txtTooltip.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtTooltip.ScrollBars"))); this.txtTooltip.Size = ((System.Drawing.Size)(resources.GetObject("txtTooltip.Size"))); this.txtTooltip.TabIndex = ((int)(resources.GetObject("txtTooltip.TabIndex"))); this.txtTooltip.Text = resources.GetString("txtTooltip.Text"); this.txtTooltip.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtTooltip.TextAlign"))); this.txtTooltip.Visible = ((bool)(resources.GetObject("txtTooltip.Visible"))); this.txtTooltip.WordWrap = ((bool)(resources.GetObject("txtTooltip.WordWrap"))); // // label5 // this.label5.AccessibleDescription = resources.GetString("label5.AccessibleDescription"); this.label5.AccessibleName = resources.GetString("label5.AccessibleName"); this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label5.Anchor"))); this.label5.AutoSize = ((bool)(resources.GetObject("label5.AutoSize"))); this.label5.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label5.Dock"))); this.label5.Enabled = ((bool)(resources.GetObject("label5.Enabled"))); this.errorProvider.SetError(this.label5, resources.GetString("label5.Error")); this.label5.Font = ((System.Drawing.Font)(resources.GetObject("label5.Font"))); this.errorProvider.SetIconAlignment(this.label5, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("label5.IconAlignment")))); this.errorProvider.SetIconPadding(this.label5, ((int)(resources.GetObject("label5.IconPadding")))); this.label5.Image = ((System.Drawing.Image)(resources.GetObject("label5.Image"))); this.label5.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label5.ImageAlign"))); this.label5.ImageIndex = ((int)(resources.GetObject("label5.ImageIndex"))); this.label5.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label5.ImeMode"))); this.label5.Location = ((System.Drawing.Point)(resources.GetObject("label5.Location"))); this.label5.Name = "label5"; this.label5.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label5.RightToLeft"))); this.label5.Size = ((System.Drawing.Size)(resources.GetObject("label5.Size"))); this.label5.TabIndex = ((int)(resources.GetObject("label5.TabIndex"))); this.label5.Text = resources.GetString("label5.Text"); this.label5.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label5.TextAlign"))); this.label5.Visible = ((bool)(resources.GetObject("label5.Visible"))); // // txtDescription // this.txtDescription.AccessibleDescription = resources.GetString("txtDescription.AccessibleDescription"); this.txtDescription.AccessibleName = resources.GetString("txtDescription.AccessibleName"); this.txtDescription.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("txtDescription.Anchor"))); this.txtDescription.AutoSize = ((bool)(resources.GetObject("txtDescription.AutoSize"))); this.txtDescription.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("txtDescription.BackgroundImage"))); this.txtDescription.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("txtDescription.Dock"))); this.txtDescription.Enabled = ((bool)(resources.GetObject("txtDescription.Enabled"))); this.errorProvider.SetError(this.txtDescription, resources.GetString("txtDescription.Error")); this.txtDescription.Font = ((System.Drawing.Font)(resources.GetObject("txtDescription.Font"))); this.errorProvider.SetIconAlignment(this.txtDescription, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("txtDescription.IconAlignment")))); this.errorProvider.SetIconPadding(this.txtDescription, ((int)(resources.GetObject("txtDescription.IconPadding")))); this.txtDescription.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("txtDescription.ImeMode"))); this.txtDescription.Location = ((System.Drawing.Point)(resources.GetObject("txtDescription.Location"))); this.txtDescription.MaxLength = ((int)(resources.GetObject("txtDescription.MaxLength"))); this.txtDescription.Multiline = ((bool)(resources.GetObject("txtDescription.Multiline"))); this.txtDescription.Name = "txtDescription"; this.txtDescription.PasswordChar = ((char)(resources.GetObject("txtDescription.PasswordChar"))); this.txtDescription.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("txtDescription.RightToLeft"))); this.txtDescription.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("txtDescription.ScrollBars"))); this.txtDescription.Size = ((System.Drawing.Size)(resources.GetObject("txtDescription.Size"))); this.txtDescription.TabIndex = ((int)(resources.GetObject("txtDescription.TabIndex"))); this.txtDescription.Text = resources.GetString("txtDescription.Text"); this.txtDescription.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("txtDescription.TextAlign"))); this.txtDescription.Visible = ((bool)(resources.GetObject("txtDescription.Visible"))); this.txtDescription.WordWrap = ((bool)(resources.GetObject("txtDescription.WordWrap"))); // // openFileDialog // this.openFileDialog.DefaultExt = "snk"; this.openFileDialog.Filter = resources.GetString("openFileDialog.Filter"); this.openFileDialog.Title = resources.GetString("openFileDialog.Title"); // // WzPageResourceSetup // this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.Controls.Add(this.txtTooltip); this.Controls.Add(this.label5); this.Controls.Add(this.txtDescription); this.Controls.Add(this.label3); this.Controls.Add(this.txtName); this.Controls.Add(this.label1); this.Controls.Add(this.txtId); this.Controls.Add(this.label2); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.errorProvider.SetError(this, resources.GetString("$this.Error")); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.errorProvider.SetIconAlignment(this, ((System.Windows.Forms.ErrorIconAlignment)(resources.GetObject("$this.IconAlignment")))); this.errorProvider.SetIconPadding(this, ((int)(resources.GetObject("$this.IconPadding")))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.Name = "WzPageResourceSetup"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.Size = ((System.Drawing.Size)(resources.GetObject("$this.Size"))); this.SubTitle = "Specify Functoid Properties"; this.Title = "Functoid Properties"; this.Leave += new System.EventHandler(this.WzPageResourceSetup_Leave); this.Controls.SetChildIndex(this.label2, 0); this.Controls.SetChildIndex(this.txtId, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.txtName, 0); this.Controls.SetChildIndex(this.label3, 0); this.Controls.SetChildIndex(this.txtDescription, 0); this.Controls.SetChildIndex(this.label5, 0); this.Controls.SetChildIndex(this.txtTooltip, 0); this.Controls.SetChildIndex(this.panelHeader, 0); this.panelHeader.ResumeLayout(false); this.ResumeLayout(false); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Automation { /// <summary> /// Service operation for automation type fields. (see /// http://aka.ms/azureautomationsdk/typefieldoperations for more /// information) /// </summary> internal partial class TypeFieldOperations : IServiceOperations<AutomationManagementClient>, ITypeFieldOperations { /// <summary> /// Initializes a new instance of the TypeFieldOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal TypeFieldOperations(AutomationManagementClient client) { this._client = client; } private AutomationManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Automation.AutomationManagementClient. /// </summary> public AutomationManagementClient Client { get { return this._client; } } /// <summary> /// Retrieve a list of fields of a given type identified by module /// name. (see http://aka.ms/azureautomationsdk/typefieldoperations /// for more information) /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The name of module. /// </param> /// <param name='typeName'> /// Required. The name of type. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the list fields operation. /// </returns> public async Task<TypeFieldListResponse> ListAsync(string resourceGroupName, string automationAccount, string moduleName, string typeName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (automationAccount == null) { throw new ArgumentNullException("automationAccount"); } if (moduleName == null) { throw new ArgumentNullException("moduleName"); } if (typeName == null) { throw new ArgumentNullException("typeName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccount", automationAccount); tracingParameters.Add("moduleName", moduleName); tracingParameters.Add("typeName", typeName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ResourceNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); } url = url + "/automationAccounts/"; url = url + Uri.EscapeDataString(automationAccount); url = url + "/modules/"; url = url + Uri.EscapeDataString(moduleName); url = url + "/types/"; url = url + Uri.EscapeDataString(typeName); url = url + "/fields"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2017-05-15-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); httpRequest.Headers.Add("ocp-referer", url); httpRequest.Headers.Add("x-ms-version", "2014-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result TypeFieldListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new TypeFieldListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { TypeField typeFieldInstance = new TypeField(); result.Fields.Add(typeFieldInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); typeFieldInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); typeFieldInstance.Type = typeInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; using System.Diagnostics.Contracts; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography { /// <summary> /// Flags providing information about a raw key handle being opened /// </summary> [Flags] public enum CngKeyHandleOpenOptions { None = 0x00000000, /// <summary> /// The key handle being opened represents an ephemeral key /// </summary> EphemeralKey = 0x00000001 } /// <summary> /// Managed representation of an NCrypt key /// </summary> [System.Security.Permissions.HostProtection(MayLeakOnAbort = true)] public sealed class CngKey : IDisposable { private SafeNCryptKeyHandle m_keyHandle; private SafeNCryptProviderHandle m_kspHandle; [System.Security.SecurityCritical] private CngKey(SafeNCryptProviderHandle kspHandle, SafeNCryptKeyHandle keyHandle) { Contract.Requires(keyHandle != null && !keyHandle.IsInvalid && !keyHandle.IsClosed); Contract.Requires(kspHandle != null && !kspHandle.IsInvalid && !kspHandle.IsClosed); Contract.Ensures(m_keyHandle != null && !m_keyHandle.IsInvalid && !m_keyHandle.IsClosed); Contract.Ensures(kspHandle != null && !kspHandle.IsInvalid && !kspHandle.IsClosed); m_keyHandle = keyHandle; m_kspHandle = kspHandle; } // // Key properties // /// <summary> /// Algorithm group this key can be used with /// </summary> public CngAlgorithmGroup AlgorithmGroup { [SecuritySafeCritical] [Pure] get { Contract.Assert(m_keyHandle != null); string group = NCryptNative.GetPropertyAsString(m_keyHandle, NCryptNative.KeyPropertyName.AlgorithmGroup, CngPropertyOptions.None); if (group == null) { return null; } else { return new CngAlgorithmGroup(group); } } } /// <summary> /// Name of the algorithm this key can be used with /// </summary> public CngAlgorithm Algorithm { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); string algorithm = NCryptNative.GetPropertyAsString(m_keyHandle, NCryptNative.KeyPropertyName.Algorithm, CngPropertyOptions.None); return new CngAlgorithm(algorithm); } } /// <summary> /// Export restrictions on the key /// </summary> public CngExportPolicies ExportPolicy { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); int policy = NCryptNative.GetPropertyAsDWord(m_keyHandle, NCryptNative.KeyPropertyName.ExportPolicy, CngPropertyOptions.None); return (CngExportPolicies)policy; } } /// <summary> /// Native handle for the key /// </summary> public SafeNCryptKeyHandle Handle { [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] get { Contract.Assert(m_keyHandle != null); return m_keyHandle.Duplicate(); } } /// <summary> /// Is this key ephemeral or persisted /// </summary> /// <remarks> /// Any ephemeral key created by the CLR will have a property 'CLR IsEphemeral' which consists /// of a single byte containing the value 1. We cannot detect ephemeral keys created by other /// APIs and imported via handle. /// </remarks> public bool IsEphemeral { [SecuritySafeCritical] [Pure] get { Contract.Assert(m_keyHandle != null); bool foundProperty; byte[] ephemeralProperty = null; try { ephemeralProperty = NCryptNative.GetProperty(m_keyHandle, NCryptNative.KeyPropertyName.ClrIsEphemeral, CngPropertyOptions.CustomProperty, out foundProperty); } catch (CryptographicException) { // Third party Key providers, and Windows PCP KSP won't recognize this property; // and Win32 layer does not enforce error return contract. // Therefore, they can return whatever error code they think appropriate. return false; } return foundProperty && ephemeralProperty != null && ephemeralProperty.Length == 1 && ephemeralProperty[0] == 1; } [System.Security.SecurityCritical] private set { Contract.Assert(m_keyHandle != null); NCryptNative.SetProperty(m_keyHandle, NCryptNative.KeyPropertyName.ClrIsEphemeral, new byte[] { value ? (byte)1 : (byte)0 }, CngPropertyOptions.CustomProperty); } } /// <summary> /// Is this a machine key or a user key /// </summary> public bool IsMachineKey { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); int type = NCryptNative.GetPropertyAsDWord(m_keyHandle, NCryptNative.KeyPropertyName.KeyType, CngPropertyOptions.None); return ((CngKeyTypes)type & CngKeyTypes.MachineKey) == CngKeyTypes.MachineKey; } } /// <summary> /// The name of the key, null if it is ephemeral. We can only detect ephemeral keys created by /// the CLR. Other ephemeral keys, such as those imported by handle, will get a CryptographicException /// if they read this property. /// </summary> public string KeyName { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); if (IsEphemeral) { return null; } else { return NCryptNative.GetPropertyAsString(m_keyHandle, NCryptNative.KeyPropertyName.Name, CngPropertyOptions.None); } } } /// <summary> /// Size, in bits, of the key /// </summary> public int KeySize { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); return NCryptNative.GetPropertyAsDWord(m_keyHandle, NCryptNative.KeyPropertyName.Length, CngPropertyOptions.None); } } /// <summary> /// Usage restrictions on the key /// </summary> public CngKeyUsages KeyUsage { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); int keyUsage = NCryptNative.GetPropertyAsDWord(m_keyHandle, NCryptNative.KeyPropertyName.KeyUsage, CngPropertyOptions.None); return (CngKeyUsages)keyUsage; } } /// <summary> /// HWND of the window to use as a parent for any UI /// </summary> public IntPtr ParentWindowHandle { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); return NCryptNative.GetPropertyAsIntPtr(m_keyHandle, NCryptNative.KeyPropertyName.ParentWindowHandle, CngPropertyOptions.None); } [SecuritySafeCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] set { Contract.Assert(m_keyHandle != null); NCryptNative.SetProperty(m_keyHandle, NCryptNative.KeyPropertyName.ParentWindowHandle, value, CngPropertyOptions.None); } } /// <summary> /// KSP which holds this key /// </summary> public CngProvider Provider { [SecuritySafeCritical] get { Contract.Assert(m_kspHandle != null); string provider = NCryptNative.GetPropertyAsString(m_kspHandle, NCryptNative.ProviderPropertyName.Name, CngPropertyOptions.None); if (provider == null) { return null; } else { return new CngProvider(provider); } } } /// <summary> /// Native handle to the KSP associated with this key /// </summary> public SafeNCryptProviderHandle ProviderHandle { [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] get { Contract.Assert(m_kspHandle != null); return m_kspHandle.Duplicate(); } } /// <summary> /// Unique name of the key, null if it is ephemeral. See the comments on the Name property for /// details about names of ephemeral keys. /// </summary> public string UniqueName { [SecuritySafeCritical] get { Contract.Assert(m_keyHandle != null); if (IsEphemeral) { return null; } else { return NCryptNative.GetPropertyAsString(m_keyHandle, NCryptNative.KeyPropertyName.UniqueName, CngPropertyOptions.None); } } } /// <summary> /// UI strings associated with a key /// </summary> public CngUIPolicy UIPolicy { [SecuritySafeCritical] get { Contract.Ensures(Contract.Result<CngUIPolicy>() != null); Contract.Assert(m_keyHandle != null); NCryptNative.NCRYPT_UI_POLICY uiPolicy = NCryptNative.GetPropertyAsStruct<NCryptNative.NCRYPT_UI_POLICY>(m_keyHandle, NCryptNative.KeyPropertyName.UIPolicy, CngPropertyOptions.None); string useContext = NCryptNative.GetPropertyAsString(m_keyHandle, NCryptNative.KeyPropertyName.UseContext, CngPropertyOptions.None); return new CngUIPolicy(uiPolicy.dwFlags, uiPolicy.pszFriendlyName, uiPolicy.pszDescription, useContext, uiPolicy.pszCreationTitle); } } /// <summary> /// Build a key container permission for the specified access to this key /// /// If the key is a known ephemeral key, return null, since we don't require permission to work with /// those keys. Otherwise return a permission scoped to the specific key and ksp if we can get those /// values, defaulting back to a full KeyContainerPermission if we cannot. /// </summary> [SecuritySafeCritical] [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity", Justification = "The demand is based on a non-mutable value type")] internal KeyContainerPermission BuildKeyContainerPermission(KeyContainerPermissionFlags flags) { Contract.Ensures(Contract.Result<KeyContainerPermission>() != null || IsEphemeral); Contract.Assert(m_keyHandle != null); Contract.Assert(m_kspHandle != null); KeyContainerPermission permission = null; if (!IsEphemeral) { // Try to get the name of the key and ksp to demand for this specific instance string keyName = null; string kspName = null; try { keyName = KeyName; kspName = NCryptNative.GetPropertyAsString(m_kspHandle, NCryptNative.ProviderPropertyName.Name, CngPropertyOptions.None); } catch (CryptographicException) { /* This may have been an imported ephemeral key */ } if (keyName != null) { KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, flags); access.ProviderName = kspName; permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); } else { permission = new KeyContainerPermission(flags); } } return permission; } // // Creation factory methods // public static CngKey Create(CngAlgorithm algorithm) { Contract.Ensures(Contract.Result<CngKey>() != null); return Create(algorithm, null); } public static CngKey Create(CngAlgorithm algorithm, string keyName) { Contract.Ensures(Contract.Result<CngKey>() != null); return Create(algorithm, keyName, null); } [SecuritySafeCritical] public static CngKey Create(CngAlgorithm algorithm, string keyName, CngKeyCreationParameters creationParameters) { Contract.Ensures(Contract.Result<CngKey>() != null); if (algorithm == null) { throw new ArgumentNullException("algorithm"); } if (creationParameters == null) { creationParameters = new CngKeyCreationParameters(); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // If we're not creating an ephemeral key, then we need to ensure the user has access to the key name if (keyName != null) { KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Create); access.ProviderName = creationParameters.Provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); } // // Create the native handles representing the new key, setup the creation parameters on it, and // finalize it for use. // SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(creationParameters.Provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.CreatePersistedKey(kspHandle, algorithm.Algorithm, keyName, creationParameters.KeyCreationOptions); SetKeyProperties(keyHandle, creationParameters); NCryptNative.FinalizeKey(keyHandle); CngKey key = new CngKey(kspHandle, keyHandle); // No name translates to an ephemeral key if (keyName == null) { key.IsEphemeral = true; } return key; } /// <summary> /// Delete this key /// </summary> [SecuritySafeCritical] public void Delete() { Contract.Assert(m_keyHandle != null); // Make sure we have permission to delete this key KeyContainerPermission permission = BuildKeyContainerPermission(KeyContainerPermissionFlags.Delete); if (permission != null) { permission.Demand(); } NCryptNative.DeleteKey(m_keyHandle); // Once the key is deleted, the handles are no longer valid so dispose of this instance Dispose(); } [SecuritySafeCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public void Dispose() { if (m_kspHandle != null) { m_kspHandle.Dispose(); } if (m_keyHandle != null) { m_keyHandle.Dispose(); } } // // Check to see if a key already exists // public static bool Exists(string keyName) { return Exists(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static bool Exists(string keyName, CngProvider provider) { return Exists(keyName, provider, CngKeyOpenOptions.None); } [SecuritySafeCritical] [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Reviewed")] public static bool Exists(string keyName, CngProvider provider, CngKeyOpenOptions options) { if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } using (SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider)) { SafeNCryptKeyHandle keyHandle = null; try { NCryptNative.ErrorCode error = NCryptNative.UnsafeNativeMethods.NCryptOpenKey(kspHandle, out keyHandle, keyName, 0, options); // CNG will return either NTE_NOT_FOUND or NTE_BAD_KEYSET for the case where the key does // not exist, so we need to check for both return codes. bool keyNotFound = error == NCryptNative.ErrorCode.KeyDoesNotExist || error == NCryptNative.ErrorCode.NotFound; if (error != NCryptNative.ErrorCode.Success && !keyNotFound) { throw new CryptographicException((int)error); } return error == NCryptNative.ErrorCode.Success; } finally { if (keyHandle != null) { keyHandle.Dispose(); } } } } // // Import factory methods // public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format) { Contract.Ensures(Contract.Result<CngKey>() != null); return Import(keyBlob, format, CngProvider.MicrosoftSoftwareKeyStorageProvider); } [SecuritySafeCritical] public static CngKey Import(byte[] keyBlob, CngKeyBlobFormat format, CngProvider provider) { Contract.Ensures(Contract.Result<CngKey>() != null); if (keyBlob == null) { throw new ArgumentNullException("keyBlob"); } if (format == null) { throw new ArgumentNullException("format"); } if (provider == null) { throw new ArgumentNullException("provider"); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // If we don't know for sure that the key will be ephemeral, then we need to demand Import // permission. Since we won't know the name of the key until it's too late, we demand a full Import // rather than one scoped to the key. bool safeKeyImport = format == CngKeyBlobFormat.EccPublicBlob || format == CngKeyBlobFormat.GenericPublicBlob; if (!safeKeyImport) { new KeyContainerPermission(KeyContainerPermissionFlags.Import).Demand(); } // Import the key into the KSP SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.ImportKey(kspHandle, keyBlob, format.Format); // Prepare the key for use CngKey key = new CngKey(kspHandle, keyHandle); // We can't tell directly if an OpaqueTransport blob imported as an ephemeral key or not key.IsEphemeral = format != CngKeyBlobFormat.OpaqueTransportBlob; return key; } /// <summary> /// Export the key out of the KSP /// </summary> [SecuritySafeCritical] public byte[] Export(CngKeyBlobFormat format) { Contract.Assert(m_keyHandle != null); if (format == null) { throw new ArgumentNullException("format"); } KeyContainerPermission permission = BuildKeyContainerPermission(KeyContainerPermissionFlags.Export); if (permission != null) { permission.Demand(); } return NCryptNative.ExportKey(m_keyHandle, format.Format); } /// <summary> /// Get the value of an arbitrary property /// </summary> [SecuritySafeCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public CngProperty GetProperty(string name, CngPropertyOptions options) { Contract.Assert(m_keyHandle != null); if (name == null) { throw new ArgumentNullException("name"); } bool foundProperty; byte[] value = NCryptNative.GetProperty(m_keyHandle, name, options, out foundProperty); if (!foundProperty) { throw new CryptographicException((int)NCryptNative.ErrorCode.NotFound); } return new CngProperty(name, value, options); } /// <summary> /// Determine if a property exists on the key /// </summary> [SecuritySafeCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public bool HasProperty(string name, CngPropertyOptions options) { Contract.Assert(m_keyHandle != null); if (name == null) { throw new ArgumentNullException("name"); } bool foundProperty; NCryptNative.GetProperty(m_keyHandle, name, options, out foundProperty); return foundProperty; } // // Open factory methods // public static CngKey Open(string keyName) { Contract.Ensures(Contract.Result<CngKey>() != null); return Open(keyName, CngProvider.MicrosoftSoftwareKeyStorageProvider); } public static CngKey Open(string keyName, CngProvider provider) { Contract.Ensures(Contract.Result<CngKey>() != null); return Open(keyName, provider, CngKeyOpenOptions.None); } [SecuritySafeCritical] public static CngKey Open(string keyName, CngProvider provider, CngKeyOpenOptions openOptions) { Contract.Ensures(Contract.Result<CngKey>() != null); if (keyName == null) { throw new ArgumentNullException("keyName"); } if (provider == null) { throw new ArgumentNullException("provider"); } // Make sure that NCrypt is supported on this platform if (!NCryptNative.NCryptSupported) { throw new PlatformNotSupportedException(SR.GetString(SR.Cryptography_PlatformNotSupported)); } // Ensure the user has access to the key name KeyContainerPermissionAccessEntry access = new KeyContainerPermissionAccessEntry(keyName, KeyContainerPermissionFlags.Open); access.ProviderName = provider.Provider; KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags); permission.AccessEntries.Add(access); permission.Demand(); // Open the key SafeNCryptProviderHandle kspHandle = NCryptNative.OpenStorageProvider(provider.Provider); SafeNCryptKeyHandle keyHandle = NCryptNative.OpenKey(kspHandle, keyName, openOptions); return new CngKey(kspHandle, keyHandle); } /// <summary> /// Wrap an existing key handle with a CngKey object /// </summary> [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public static CngKey Open(SafeNCryptKeyHandle keyHandle, CngKeyHandleOpenOptions keyHandleOpenOptions) { if (keyHandle == null) { throw new ArgumentNullException("keyHandle"); } if (keyHandle.IsClosed || keyHandle.IsInvalid) { throw new ArgumentException(SR.GetString(SR.Cryptography_OpenInvalidHandle), "keyHandle"); } SafeNCryptKeyHandle keyHandleCopy = keyHandle.Duplicate(); // Get a handle to the key's KSP SafeNCryptProviderHandle kspHandle = new SafeNCryptProviderHandle(); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { IntPtr rawHandle = NCryptNative.GetPropertyAsIntPtr(keyHandle, NCryptNative.KeyPropertyName.ProviderHandle, CngPropertyOptions.None); kspHandle.SetHandleValue (rawHandle); } // Setup a key object wrapping the handle CngKey key = null; bool keyFullySetup = false; try { key = new CngKey(kspHandle, keyHandleCopy); bool openingEphemeralKey = (keyHandleOpenOptions & CngKeyHandleOpenOptions.EphemeralKey) == CngKeyHandleOpenOptions.EphemeralKey; // // If we're wrapping a handle to an ephemeral key, we need to make sure that IsEphemeral is // setup to return true. In the case that the handle is for an ephemeral key that was created // by the CLR, then we don't have anything to do as the IsEphemeral CLR property will already // be setup. However, if the key was created outside of the CLR we will need to setup our // ephemeral detection property. // // This enables consumers of CngKey objects to always be able to rely on the result of // calling IsEphemeral, and also allows them to safely access the Name property. // // Finally, if we detect that this is an ephemeral key that the CLR created but we were not // told that it was an ephemeral key we'll throw an exception. This prevents us from having // to decide who to believe -- the key property or the caller of the API. Since other code // relies on the ephemeral flag being set properly to avoid tripping over bugs in CNG, we // need to reject the case that we suspect that the flag is incorrect. // if (!key.IsEphemeral && openingEphemeralKey) { key.IsEphemeral = true; } else if (key.IsEphemeral && !openingEphemeralKey) { throw new ArgumentException(SR.GetString(SR.Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag), "keyHandleOpenOptions"); } keyFullySetup = true; } finally { // Make sure that we don't leak the handle the CngKey duplicated if (!keyFullySetup && key != null) { key.Dispose(); } } return key; } /// <summary> /// Setup the key properties specified in the key creation parameters /// </summary> /// <param name="keyHandle"></param> /// <param name="creationParameters"></param> [System.Security.SecurityCritical] private static void SetKeyProperties(SafeNCryptKeyHandle keyHandle, CngKeyCreationParameters creationParameters) { Contract.Requires(keyHandle != null && !keyHandle.IsInvalid && !keyHandle.IsClosed); Contract.Requires(creationParameters != null); // // Setup the well-known properties. // if (creationParameters.ExportPolicy.HasValue) { NCryptNative.SetProperty(keyHandle, NCryptNative.KeyPropertyName.ExportPolicy, (int)creationParameters.ExportPolicy.Value, CngPropertyOptions.Persist); } if (creationParameters.KeyUsage.HasValue) { NCryptNative.SetProperty(keyHandle, NCryptNative.KeyPropertyName.KeyUsage, (int)creationParameters.KeyUsage.Value, CngPropertyOptions.Persist); } if (creationParameters.ParentWindowHandle != IntPtr.Zero) { NCryptNative.SetProperty(keyHandle, NCryptNative.KeyPropertyName.ParentWindowHandle, creationParameters.ParentWindowHandle, CngPropertyOptions.None); } if (creationParameters.UIPolicy != null) { NCryptNative.NCRYPT_UI_POLICY uiPolicy = new NCryptNative.NCRYPT_UI_POLICY(); uiPolicy.dwVersion = 1; uiPolicy.dwFlags = creationParameters.UIPolicy.ProtectionLevel; uiPolicy.pszCreationTitle = creationParameters.UIPolicy.CreationTitle; uiPolicy.pszFriendlyName = creationParameters.UIPolicy.FriendlyName; uiPolicy.pszDescription = creationParameters.UIPolicy.Description; NCryptNative.SetProperty(keyHandle, NCryptNative.KeyPropertyName.UIPolicy, uiPolicy, CngPropertyOptions.Persist); // The use context is a seperate property from the standard UI context if (creationParameters.UIPolicy.UseContext != null) { NCryptNative.SetProperty(keyHandle, NCryptNative.KeyPropertyName.UseContext, creationParameters.UIPolicy.UseContext, CngPropertyOptions.Persist); } } // Iterate over the custom properties, setting those as well. foreach (CngProperty property in creationParameters.ParametersNoDemand) { NCryptNative.SetProperty(keyHandle, property.Name, property.Value, property.Options); } } /// <summary> /// Set an arbitrary property on the key /// </summary> [SecuritySafeCritical] [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] public void SetProperty(CngProperty property) { Contract.Assert(m_keyHandle != null); NCryptNative.SetProperty(m_keyHandle, property.Name, property.Value, property.Options); } } }
// TRAP message PDU (SNMP version 1 only). // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other 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. /* * Created by SharpDevelop. * User: lextm * Date: 2008/4/30 * Time: 21:22 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; namespace Lextm.SharpSnmpLib { /// <summary> /// Trap v1 PDU. /// </summary> /// <remarks>represents the PDU of trap v1 message.</remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pdu")] public sealed class TrapV1Pdu : ISnmpPdu { private byte[] _raw; private readonly Integer32 _generic; private readonly Integer32 _specific; private readonly Sequence _varbindSection; private readonly byte[] _length; /// <summary> /// Creates a <see cref="TrapV1Pdu"/> instance with PDU elements. /// </summary> /// <param name="enterprise">Enterprise</param> /// <param name="agent">Agent address</param> /// <param name="generic">Generic trap type</param> /// <param name="specific">Specific trap type</param> /// <param name="timestamp">Time stamp</param> /// <param name="variables">Variable binds</param> [CLSCompliant(false)] public TrapV1Pdu(uint[] enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) : this(new ObjectIdentifier(enterprise), agent, generic, specific, timestamp, variables) { } /// <summary> /// Creates a <see cref="TrapV1Pdu"/> instance with PDU elements. /// </summary> /// <param name="enterprise">Enterprise</param> /// <param name="agent">Agent address</param> /// <param name="generic">Generic trap type</param> /// <param name="specific">Specific trap type</param> /// <param name="timestamp">Time stamp</param> /// <param name="variables">Variable binds</param> public TrapV1Pdu(ObjectIdentifier enterprise, IP agent, Integer32 generic, Integer32 specific, TimeTicks timestamp, IList<Variable> variables) { if (enterprise == null) { throw new ArgumentNullException("enterprise"); } if (agent == null) { throw new ArgumentNullException("agent"); } if (generic == null) { throw new ArgumentNullException("generic"); } if (specific == null) { throw new ArgumentNullException("specific"); } if (timestamp == null) { throw new ArgumentNullException("timestamp"); } if (variables == null) { throw new ArgumentNullException("variables"); } Enterprise = enterprise; AgentAddress = agent; _generic = generic; _specific = specific; TimeStamp = timestamp; _varbindSection = Variable.Transform(variables); Variables = variables; } /// <summary> /// Initializes a new instance of the <see cref="TrapV1Pdu"/> class. /// </summary> /// <param name="length">The length data.</param> /// <param name="stream">The stream.</param> public TrapV1Pdu(Tuple<int, byte[]> length, Stream stream) { if (length == null) { throw new ArgumentNullException("length"); } if (stream == null) { throw new ArgumentNullException("stream"); } Enterprise = (ObjectIdentifier)DataFactory.CreateSnmpData(stream); AgentAddress = (IP)DataFactory.CreateSnmpData(stream); _generic = (Integer32)DataFactory.CreateSnmpData(stream); _specific = (Integer32)DataFactory.CreateSnmpData(stream); TimeStamp = (TimeTicks)DataFactory.CreateSnmpData(stream); _varbindSection = (Sequence)DataFactory.CreateSnmpData(stream); Variables = Variable.Transform(_varbindSection); _length = length.Item2; } /// <summary> /// Gets the request ID. /// </summary> /// <value>The request ID.</value> public Integer32 RequestId { get { throw new NotSupportedException(); } } /// <summary> /// Gets the index of the error. /// </summary> /// <value>The index of the error.</value> public Integer32 ErrorIndex { get { throw new NotSupportedException(); } } /// <summary> /// Gets the error status. /// </summary> /// <value>The error status.</value> public Integer32 ErrorStatus { get { throw new NotSupportedException(); } } /// <summary> /// Type code. /// </summary> public SnmpType TypeCode { get { return SnmpType.TrapV1Pdu; } } /// <summary> /// Appends the bytes to <see cref="Stream"/>. /// </summary> /// <param name="stream">The stream.</param> public void AppendBytesTo(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (_raw == null) { _raw = ByteTool.ParseItems(Enterprise, AgentAddress, _generic, _specific, TimeStamp, _varbindSection); } stream.AppendBytes(TypeCode, _length, _raw); } /// <summary> /// Enterprise. /// </summary> public ObjectIdentifier Enterprise { get; private set; } /// <summary> /// Agent address. /// </summary> public IP AgentAddress { get; private set; } /// <summary> /// Generic trap type. /// </summary> public GenericCode Generic { get { return (GenericCode)_generic.ToInt32(); } } /// <summary> /// Specific trap type. /// </summary> public int Specific { get { return _specific.ToInt32(); } } /// <summary> /// Time stamp. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp")] public TimeTicks TimeStamp { get; private set; } /// <summary> /// Variable binds. /// </summary> public IList<Variable> Variables { get; private set; } /// <summary> /// Returns a <see cref="string"/> that represents this <see cref="TrapV1Pdu"/>. /// </summary> /// <returns></returns> public override string ToString() { return ToString(null); } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <param name="objects">The objects.</param> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> [CLSCompliant(false)] public string ToString(IObjectRegistry objects) { return string.Format( CultureInfo.InvariantCulture, "SNMPv1 TRAP PDU: agent address: {0}; time stamp: {1}; enterprise: {2}; generic: {3}; specific: {4}; varbind count: {5}", AgentAddress, TimeStamp, Enterprise.ToString(objects), Generic, Specific.ToString(CultureInfo.InvariantCulture), Variables.Count.ToString(CultureInfo.InvariantCulture)); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Core.SiteClassificationWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
// 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.IO; using System.IO.Compression; using System.Net.Http.Headers; using System.Runtime.InteropServices; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal static class WinHttpResponseParser { private const string EncodingNameDeflate = "DEFLATE"; private const string EncodingNameGzip = "GZIP"; public static HttpResponseMessage CreateResponseMessage( WinHttpRequestState state, bool doManualDecompressionCheck) { HttpRequestMessage request = state.RequestMessage; SafeWinHttpHandle requestHandle = state.RequestHandle; CookieUsePolicy cookieUsePolicy = state.Handler.CookieUsePolicy; CookieContainer cookieContainer = state.Handler.CookieContainer; var response = new HttpResponseMessage(); bool stripEncodingHeaders = false; // Create a single buffer to use for all subsequent WinHttpQueryHeaders string interop calls. // This buffer is the length needed for WINHTTP_QUERY_RAW_HEADERS_CRLF, which includes the status line // and all headers separated by CRLF, so it should be large enough for any individual status line or header queries. int bufferLength = GetResponseHeaderCharBufferLength(requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF); char[] buffer = new char[bufferLength]; // Get HTTP version, status code, reason phrase from the response headers. int versionLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_VERSION, buffer); response.Version = CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.1", buffer, 0, versionLength) ? HttpVersion.Version11 : CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase("HTTP/1.0", buffer, 0, versionLength) ? HttpVersion.Version10 : HttpVersion.Unknown; response.StatusCode = (HttpStatusCode)GetResponseHeaderNumberInfo( requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE); int reasonPhraseLength = GetResponseHeader(requestHandle, Interop.WinHttp.WINHTTP_QUERY_STATUS_TEXT, buffer); if (reasonPhraseLength > 0) { response.ReasonPhrase = GetReasonPhrase(response.StatusCode, buffer, reasonPhraseLength); } // Create response stream and wrap it in a StreamContent object. var responseStream = new WinHttpResponseStream(state); Stream decompressedStream = responseStream; if (doManualDecompressionCheck) { int contentEncodingStartIndex = 0; int contentEncodingLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_CONTENT_ENCODING, buffer); CharArrayHelpers.Trim(buffer, ref contentEncodingStartIndex, ref contentEncodingLength); if (contentEncodingLength > 0) { if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameGzip, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new GZipStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } else if (CharArrayHelpers.EqualsOrdinalAsciiIgnoreCase( EncodingNameDeflate, buffer, contentEncodingStartIndex, contentEncodingLength)) { decompressedStream = new DeflateStream(responseStream, CompressionMode.Decompress); stripEncodingHeaders = true; } } } var content = new StreamContent(decompressedStream); response.Content = content; response.RequestMessage = request; // Parse raw response headers and place them into response message. ParseResponseHeaders(requestHandle, response, buffer, stripEncodingHeaders); return response; } /// <summary> /// Returns the first header or throws if the header isn't found. /// </summary> public static uint GetResponseHeaderNumberInfo(SafeWinHttpHandle requestHandle, uint infoLevel) { uint result = 0; uint resultSize = sizeof(uint); if (!Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel | Interop.WinHttp.WINHTTP_QUERY_FLAG_NUMBER, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, ref result, ref resultSize, IntPtr.Zero)) { WinHttpException.ThrowExceptionUsingLastError(); } return result; } public unsafe static bool GetResponseHeader( SafeWinHttpHandle requestHandle, uint infoLevel, ref char[] buffer, ref uint index, out string headerValue) { const int StackLimit = 128; Debug.Assert(buffer == null || (buffer != null && buffer.Length > StackLimit)); int bufferLength; if (buffer == null) { bufferLength = StackLimit; char* pBuffer = stackalloc char[bufferLength]; if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } else { bufferLength = buffer.Length; fixed (char* pBuffer = buffer) { if (QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { headerValue = new string(pBuffer, 0, bufferLength); return true; } } } int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { headerValue = null; return false; } if (lastError == Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { buffer = new char[bufferLength]; return GetResponseHeader(requestHandle, infoLevel, ref buffer, ref index, out headerValue); } throw WinHttpException.CreateExceptionUsingError(lastError); } /// <summary> /// Fills the buffer with the header value and returns the length, or returns 0 if the header isn't found. /// </summary> private unsafe static int GetResponseHeader(SafeWinHttpHandle requestHandle, uint infoLevel, char[] buffer) { Debug.Assert(buffer != null, "buffer must not be null."); Debug.Assert(buffer.Length > 0, "buffer must not be empty."); int bufferLength = buffer.Length; uint index = 0; fixed (char* pBuffer = buffer) { if (!QueryHeaders(requestHandle, infoLevel, pBuffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND) { return 0; } Debug.Assert(lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER, "buffer must be of sufficient size."); throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } /// <summary> /// Returns the size of the char array buffer. /// </summary> private unsafe static int GetResponseHeaderCharBufferLength(SafeWinHttpHandle requestHandle, uint infoLevel) { char* buffer = null; int bufferLength = 0; uint index = 0; if (!QueryHeaders(requestHandle, infoLevel, buffer, ref bufferLength, ref index)) { int lastError = Marshal.GetLastWin32Error(); Debug.Assert(lastError != Interop.WinHttp.ERROR_WINHTTP_HEADER_NOT_FOUND); if (lastError != Interop.WinHttp.ERROR_INSUFFICIENT_BUFFER) { throw WinHttpException.CreateExceptionUsingError(lastError); } } return bufferLength; } private unsafe static bool QueryHeaders( SafeWinHttpHandle requestHandle, uint infoLevel, char* buffer, ref int bufferLength, ref uint index) { Debug.Assert(bufferLength >= 0, "bufferLength must not be negative."); // Convert the char buffer length to the length in bytes. uint bufferLengthInBytes = (uint)bufferLength * sizeof(char); // The WinHttpQueryHeaders buffer length is in bytes, // but the API actually returns Unicode characters. bool result = Interop.WinHttp.WinHttpQueryHeaders( requestHandle, infoLevel, Interop.WinHttp.WINHTTP_HEADER_NAME_BY_INDEX, new IntPtr(buffer), ref bufferLengthInBytes, ref index); // Convert the byte buffer length back to the length in chars. bufferLength = (int)bufferLengthInBytes / sizeof(char); return result; } private static string GetReasonPhrase(HttpStatusCode statusCode, char[] buffer, int bufferLength) { CharArrayHelpers.DebugAssertArrayInputs(buffer, 0, bufferLength); Debug.Assert(bufferLength > 0); // If it's a known reason phrase, use the known reason phrase instead of allocating a new string. string knownReasonPhrase = HttpStatusDescription.Get(statusCode); return (knownReasonPhrase != null && CharArrayHelpers.EqualsOrdinal(knownReasonPhrase, buffer, 0, bufferLength)) ? knownReasonPhrase : new string(buffer, 0, bufferLength); } private static void ParseResponseHeaders( SafeWinHttpHandle requestHandle, HttpResponseMessage response, char[] buffer, bool stripEncodingHeaders) { HttpResponseHeaders responseHeaders = response.Headers; HttpContentHeaders contentHeaders = response.Content.Headers; int bufferLength = GetResponseHeader( requestHandle, Interop.WinHttp.WINHTTP_QUERY_RAW_HEADERS_CRLF, buffer); var reader = new WinHttpResponseHeaderReader(buffer, 0, bufferLength); // Skip the first line which contains status code, etc. information that we already parsed. reader.ReadLine(); // Parse the array of headers and split them between Content headers and Response headers. string headerName; string headerValue; while (reader.ReadHeader(out headerName, out headerValue)) { if (!responseHeaders.TryAddWithoutValidation(headerName, headerValue)) { if (stripEncodingHeaders) { // Remove Content-Length and Content-Encoding headers if we are // decompressing the response stream in the handler (due to // WINHTTP not supporting it in a particular downlevel platform). // This matches the behavior of WINHTTP when it does decompression itself. if (string.Equals(HttpKnownHeaderNames.ContentLength, headerName, StringComparison.OrdinalIgnoreCase) || string.Equals(HttpKnownHeaderNames.ContentEncoding, headerName, StringComparison.OrdinalIgnoreCase)) { continue; } } // TODO: Issue #2165. Should we log if there is an error here? contentHeaders.TryAddWithoutValidation(headerName, headerValue); } } } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Sequence(Name = "Initiate_ResponsePDU", IsSet = false)] public class Initiate_ResponsePDU : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Initiate_ResponsePDU)); private InitResponseDetailSequenceType initResponseDetail_; private Integer32 localDetailCalled_; private bool localDetailCalled_present; private Integer8 negotiatedDataStructureNestingLevel_; private bool negotiatedDataStructureNestingLevel_present; private Integer16 negotiatedMaxServOutstandingCalled_; private Integer16 negotiatedMaxServOutstandingCalling_; [ASN1Element(Name = "localDetailCalled", IsOptional = true, HasTag = true, Tag = 0, HasDefaultValue = false)] public Integer32 LocalDetailCalled { get { return localDetailCalled_; } set { localDetailCalled_ = value; localDetailCalled_present = true; } } [ASN1Element(Name = "negotiatedMaxServOutstandingCalling", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public Integer16 NegotiatedMaxServOutstandingCalling { get { return negotiatedMaxServOutstandingCalling_; } set { negotiatedMaxServOutstandingCalling_ = value; } } [ASN1Element(Name = "negotiatedMaxServOutstandingCalled", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public Integer16 NegotiatedMaxServOutstandingCalled { get { return negotiatedMaxServOutstandingCalled_; } set { negotiatedMaxServOutstandingCalled_ = value; } } [ASN1Element(Name = "negotiatedDataStructureNestingLevel", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)] public Integer8 NegotiatedDataStructureNestingLevel { get { return negotiatedDataStructureNestingLevel_; } set { negotiatedDataStructureNestingLevel_ = value; negotiatedDataStructureNestingLevel_present = true; } } [ASN1Element(Name = "initResponseDetail", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public InitResponseDetailSequenceType InitResponseDetail { get { return initResponseDetail_; } set { initResponseDetail_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isLocalDetailCalledPresent() { return localDetailCalled_present; } public bool isNegotiatedDataStructureNestingLevelPresent() { return negotiatedDataStructureNestingLevel_present; } [ASN1PreparedElement] [ASN1Sequence(Name = "initResponseDetail", IsSet = false)] public class InitResponseDetailSequenceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(InitResponseDetailSequenceType)); private AdditionalCBBOptions additionalCbbSupportedCalled_; private AdditionalSupportOptions additionalSupportedCalled_; private ParameterSupportOptions negotiatedParameterCBB_; private Integer16 negotiatedVersionNumber_; private string privilegeClassIdentityCalled_; private ServiceSupportOptions servicesSupportedCalled_; [ASN1Element(Name = "negotiatedVersionNumber", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public Integer16 NegotiatedVersionNumber { get { return negotiatedVersionNumber_; } set { negotiatedVersionNumber_ = value; } } [ASN1Element(Name = "negotiatedParameterCBB", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public ParameterSupportOptions NegotiatedParameterCBB { get { return negotiatedParameterCBB_; } set { negotiatedParameterCBB_ = value; } } [ASN1Element(Name = "servicesSupportedCalled", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public ServiceSupportOptions ServicesSupportedCalled { get { return servicesSupportedCalled_; } set { servicesSupportedCalled_ = value; } } [ASN1Element(Name = "additionalSupportedCalled", IsOptional = true, HasTag = true, Tag = 3, HasDefaultValue = false)] public AdditionalSupportOptions AdditionalSupportedCalled { get { return additionalSupportedCalled_; } set { additionalSupportedCalled_ = value; } } [ASN1Element(Name = "additionalCbbSupportedCalled", IsOptional = true, HasTag = true, Tag = 4, HasDefaultValue = false)] public AdditionalCBBOptions AdditionalCbbSupportedCalled { get { return additionalCbbSupportedCalled_; } set { additionalCbbSupportedCalled_ = value; } } [ASN1String(Name = "", StringType = UniversalTags.VisibleString, IsUCS = false)] [ASN1Element(Name = "privilegeClassIdentityCalled", IsOptional = true, HasTag = true, Tag = 5, HasDefaultValue = false)] public string PrivilegeClassIdentityCalled { get { return privilegeClassIdentityCalled_; } set { privilegeClassIdentityCalled_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.Xml; namespace RE { internal delegate void LinkPointSignalEvent(RELinkPoint LinkPoint, RELinkPointSignalType Signal, object Data, bool MoreComing); internal partial class RELinkPanel : UserControl, IRELinkPanel { private bool isDragging = false; private bool wasDragging = false; private bool isResizing = false; private bool isSelecting = false; private int dragStartX; private int dragStartY; private int dragSelectX; private int dragSelectY; private int scrollStartX; private int scrollStartY; private int scrollSelectX; private int scrollSelectY; private int scrollDeltaX; private int scrollDeltaY; private List<LinkConnection> connections = new List<LinkConnection>(); private List<REBaseItem> selectedItems = new List<REBaseItem>(); private Point nextItemLocation = new Point(0, 0); private bool modified = false; public RELinkPanel() { InitializeComponent(); } #region Items protected override void OnControlAdded(ControlEventArgs e) { base.OnControlAdded(e); if (e.Control is REBaseItem) { modified = true; REBaseItem Item = e.Control as REBaseItem; Item.Enter += new EventHandler(Item_Enter); Control ItemCaption = Item.Controls["lblCaption"]; ItemCaption.MouseDown += new MouseEventHandler(ItemCaption_MouseDown); ItemCaption.MouseMove += new MouseEventHandler(ItemCaption_MouseMove); ItemCaption.MouseUp += new MouseEventHandler(ItemCaption_MouseUp); Control ItemResize = Item.Controls["imgItemResize"]; ItemResize.MouseDown += new MouseEventHandler(ItemResize_MouseDown); ItemResize.MouseMove += new MouseEventHandler(ItemResize_MouseMove); ItemResize.MouseUp += new MouseEventHandler(ItemResize_MouseUp); } } protected override void OnControlRemoved(ControlEventArgs e) { base.OnControlRemoved(e); if (e.Control is REBaseItem) modified = true; } public void AddItem(REBaseItem Item, bool FindNextPosition) { if (FindNextPosition) { nextItemLocation.X = 0; nextItemLocation.Y = 0; if (Controls.Count != 0) { foreach (REBaseItem Item1 in Controls) if (nextItemLocation.X < Item1.Right) nextItemLocation.X = Item1.Right; nextItemLocation.X += 8;//margin; } //TODO: if more right than visile width, then down? } //else assert set by right-click for context menu Item.Location = nextItemLocation; Controls.Add(Item); Item.BringToFront(); SelectedItem = Item; //modified = true;//see ControlAdded } public REBaseItem SelectedItem { get { //if(SelectedItems.Count>1)raise? return selectedItems.Count == 0 ? null : selectedItems[0] as REBaseItem; } set { for (int i = 0; i < selectedItems.Count; i++) (selectedItems[i] as REBaseItem).Selected = false; selectedItems.Clear(); if (value != null) { selectedItems.Add(value); (selectedItems[0] as REBaseItem).Selected = true; } } } private bool isMouseDown = false; void Item_Enter(object sender, EventArgs e) { if (!isMouseDown) SelectedItem = sender as REBaseItem; } public void ClearAllItems() { connections.Clear(); selectedItems.Clear(); Controls.Clear(); foreach (ColorStockEntry c in ColorStock) c.Count = 0; Invalidate(false); } public void SelectAllItems() { selectedItems.Clear(); foreach (REBaseItem Item1 in Controls) { selectedItems.Add(Item1); Item1.Selected = true; } } public void DeleteSelectedItems() { //TODO: undo? REBaseItem[] list = selectedItems.ToArray(); selectedItems.Clear(); foreach (REBaseItem item in list) item.Close(); } public bool Modified { get { return modified; } set { modified = value; } } private Color StrToColor(string x) { if (x == "") return Color.Black; else if (x[0] == '$') return Color.FromArgb( Int32.Parse(x.Substring(5, 2), System.Globalization.NumberStyles.HexNumber), Int32.Parse(x.Substring(3, 2), System.Globalization.NumberStyles.HexNumber), Int32.Parse(x.Substring(1, 2), System.Globalization.NumberStyles.HexNumber) ); else return Color.FromName(x); } private string ColorToStr(Color color) { return String.Format("${2:X2}{1:X2}{0:X2}", color.R, color.G, color.B); } const string REClipboardFormat = "RE_CLIPBOARD_DATA_2_0"; internal bool CanLoadClipboard() { return Clipboard.GetDataObject().GetDataPresent(REClipboardFormat); } internal int SaveClipboard(bool deleteSelectedItems) { int itemcount;// = selectedItems.Count; Cursor = Cursors.WaitCursor; try { XmlDocument xdoc = new XmlDocument(); xdoc.PreserveWhitespace = true; xdoc.LoadXml("<reClipboardData version=\"2.0\" />"); XmlElement xroot = xdoc.DocumentElement; itemcount = SaveItems(xroot, true); //TODO: extract and concat text from items? Clipboard.SetData(REClipboardFormat, xdoc.OuterXml); if (deleteSelectedItems) DeleteSelectedItems(); } finally { Cursor = Cursors.Default; } return itemcount; } internal int LoadClipboard(bool findLocation, Hashtable knownItemTypes) { int itemcount;// = selectedItems.Count; Cursor = Cursors.WaitCursor; try { XmlDocument xdoc = new XmlDocument(); xdoc.PreserveWhitespace = true; object clipboarddata=Clipboard.GetData(REClipboardFormat); XmlElement xroot = null; if (clipboarddata != null) { xdoc.LoadXml(clipboarddata as string); xroot = xdoc.DocumentElement; } if (xroot == null) throw new Exception("Clipboard does not contain RE clipboard data"); if (findLocation) nextItemLocation = new Point(0, 0); itemcount = LoadItems(xroot, knownItemTypes, true, nextItemLocation); } finally { Cursor = Cursors.Default; } return itemcount; } internal int SaveItems(XmlElement xroot, bool selectedItemsOnly) { Hashtable links = new Hashtable(); int linkrc = 1000; int itemcount = 0; foreach (REBaseItem item in (selectedItemsOnly ? (ICollection)selectedItems : (ICollection)Controls)) { XmlElement xitem = xroot.OwnerDocument.CreateElement("item"); foreach (REItemAttribute r in (item.GetType().GetCustomAttributes(typeof(REItemAttribute), true))) xitem.SetAttribute("class", r.SystemName); item.SaveToXml(xitem); if (!selectedItemsOnly) item.Modified = false; itemcount++; foreach (RELinkPoint linkpoint in item.GetLinkPoints(true)) { string linkref; if (links.Contains(linkpoint)) { linkref = links[linkpoint] as string; links.Remove(linkpoint); } else { //TODO: use GUID and try to restore on paste? linkref = String.Format("lp{0}", linkrc++); links.Add(linkpoint.ConnectedTo, linkref); } XmlElement xlink = xroot.OwnerDocument.CreateElement("link"); xlink.SetAttribute("name", linkpoint.Key); xlink.SetAttribute("ref", linkref); if (!selectedItemsOnly) xlink.SetAttribute("color", ColorToStr(linkpoint.ConnectionColor)); xitem.AppendChild(xlink); } xroot.AppendChild(xitem); } return itemcount; } internal int LoadItems(XmlElement xroot, Hashtable knownItemTypes, bool addItems, Point delta) { Hashtable links = new Hashtable(); Hashtable itemlinks = new Hashtable(); bool itemlinkslisted; List<REBaseItem> items = new List<REBaseItem>(); Point mosttopleft = new Point(0, 0); Visible = false; //SuspendLayout(); try { if (addItems) { //add to items, find suitable location when none provided if (delta.X == 0 && delta.Y == 0 && Controls.Count != 0) { foreach (REBaseItem item in Controls) if (delta.X < item.Right) delta.X = item.Right; delta.X += 8;//margin } //unselect current selection foreach (REBaseItem item in selectedItems) item.Selected = false; selectedItems.Clear(); } else { //load from file ClearAllItems(); } foreach (XmlNode xitem in xroot.ChildNodes) { if (xitem is XmlElement && xitem.Name == "item") { string sysname = (xitem as XmlElement).GetAttribute("class"); REItemType itemtype = knownItemTypes[sysname] as REItemType; if (itemtype == null) { //throw new Exception(String.Format("Unknown item type \"{0}\"", sysname)); //TODO: replace by comment? msgbox at end? } else { REBaseItem item = itemtype.CreateOne(); items.Add(item); item.LoadFromXml(xitem as XmlElement); Controls.Add(item); if (items.Count == 1) mosttopleft = item.Location; else { if (mosttopleft.X > item.Left) mosttopleft.X = item.Left; if (mosttopleft.Y > item.Top) mosttopleft.Y = item.Top; } itemlinkslisted = false; itemlinks.Clear(); foreach (XmlElement xlink in xitem.SelectNodes("link")) { string linkref = xlink.GetAttribute("ref"); if (!itemlinkslisted) { foreach (RELinkPoint linkpoint in item.GetLinkPoints(false)) itemlinks.Add(linkpoint.Key, linkpoint); itemlinkslisted = true; } if (links.Contains(linkref)) { //close link RELinkPoint lp1 = itemlinks[xlink.GetAttribute("name")] as RELinkPoint; if (!addItems) NextLinkColor = StrToColor(xlink.GetAttribute("color")); //else use link color from stock if (lp1 != null) lp1.ConnectedTo = links[linkref] as RELinkPoint; links.Remove(linkref); } else links.Add(linkref, itemlinks[xlink.GetAttribute("name")]); } } } //else ignore? //TODO: keep to save later } //check all links closed? if (!addItems) { if (mosttopleft.X > 0) mosttopleft.X = 0; if (mosttopleft.Y > 0) mosttopleft.Y = 0; } foreach (REBaseItem item in items) { item.Selected = addItems; if (addItems) selectedItems.Add(item); item.Location = new Point(item.Left - mosttopleft.X + delta.X, item.Top - mosttopleft.Y + delta.Y); } } finally { NextLinkColor = Color.Transparent; Visible = true; //ResumeLayout(); } return items.Count; } #endregion #region Mouse Actions protected override void OnMouseDown(MouseEventArgs e) { isMouseDown = true; base.OnMouseDown(e); switch (e.Button) { case MouseButtons.Left: isSelecting = true; dragStartX=e.X; dragStartY=e.Y; dragSelectX = dragStartX; dragSelectY = dragStartY; scrollStartX = dragStartX; scrollStartY = dragStartY; scrollSelectX = dragStartX; scrollSelectY = dragStartY; scrollDeltaX = HorizontalScroll.Value; scrollDeltaY = VerticalScroll.Value; break; case MouseButtons.Right: nextItemLocation.X = e.X; nextItemLocation.Y = e.Y; break; } isMouseDown = false; } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (isSelecting) { isSelecting = false; Invalidate(false); bool invertSelect = KeyboardFlags.CtrlPressed; //build selection if(!invertSelect) SelectedItem = null; if (dragSelectX > dragStartX && dragSelectY > dragStartY) { //items inside lines foreach (REBaseItem Item in Controls) if (Item.Left >= dragStartX && Item.Top >= dragStartY && Item.Right <= dragSelectX && Item.Bottom <= dragSelectY) if (invertSelect && selectedItems.Contains(Item)) { selectedItems.Remove(Item); Item.Selected = false; } else { selectedItems.Add(Item); Item.Selected = true; } } else { //items inside and crossing lines int x1 = Math.Min(dragStartX, dragSelectX); int y1 = Math.Min(dragStartY, dragSelectY); int x2 = Math.Max(dragStartX, dragSelectX); int y2 = Math.Max(dragStartY, dragSelectY); foreach (REBaseItem Item in Controls) if (Item.Left <= x2 && x1 <= Item.Right && Item.Top <= y2 && y1 <= Item.Bottom) if (invertSelect && selectedItems.Contains(Item)) { selectedItems.Remove(Item); Item.Selected = false; } else { selectedItems.Add(Item); Item.Selected = true; } } Parent.Focus(); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (isSelecting) { dragSelectX = e.X; dragSelectY = e.Y; if (KeyboardFlags.CtrlPressed) { int sx = scrollStartX + scrollDeltaX - e.X; int sy = scrollStartY + scrollDeltaY - e.Y; if (sx < HorizontalScroll.Minimum) sx = HorizontalScroll.Minimum; if (sy < VerticalScroll.Minimum) sy = VerticalScroll.Minimum; if (sx > HorizontalScroll.Maximum) sx = HorizontalScroll.Maximum; if (sy > VerticalScroll.Maximum) sy = VerticalScroll.Maximum; HorizontalScroll.Value = sx; VerticalScroll.Value = sy; dragStartX = scrollSelectX + scrollDeltaX - HorizontalScroll.Value; dragStartY = scrollSelectY + scrollDeltaY - VerticalScroll.Value; } else { scrollStartX = dragSelectX; scrollStartY = dragSelectY; scrollSelectX = dragStartX; scrollSelectY = dragStartY; scrollDeltaX = HorizontalScroll.Value; scrollDeltaY = VerticalScroll.Value; } Invalidate(false); } } void ItemCaption_MouseDown(object sender, MouseEventArgs e) { //TODO: treshold? isDragging = true; wasDragging = false; dragStartX = e.X; dragStartY = e.Y; } void ItemCaption_MouseUp(object sender, MouseEventArgs e) { isDragging = false; if (!wasDragging) { REBaseItem Item = (sender as Control).Parent as REBaseItem; if (KeyboardFlags.CtrlPressed) { if (selectedItems.Contains(Item)) { selectedItems.Remove(Item); Item.Selected = false; } else { selectedItems.Add(Item); Item.Selected = true; } } else { SelectedItem = Item; (Item as REBaseItem).ItemSelectFocus();//Item.Focus(); } } } void ItemCaption_MouseMove(object sender, MouseEventArgs e) { if (isDragging) { //TODO: dragging treshold if (!wasDragging) { REBaseItem Item = (sender as Control).Parent as REBaseItem; if (!selectedItems.Contains(Item)) if (KeyboardFlags.CtrlPressed) { selectedItems.Add(Item); Item.Selected = true; } else SelectedItem = Item; } wasDragging = true; int dx = e.X - dragStartX; int dy = e.Y - dragStartY; int sx = -HorizontalScroll.Value; int sy = -VerticalScroll.Value; foreach (REBaseItem Item1 in selectedItems) { if (Item1.Left + dx < sx) dx = -Item1.Left + sx; if (Item1.Top + dy < sy) dy = -Item1.Top + sy; } if (!(dx == 0 && dy == 0)) { foreach (REBaseItem Item1 in selectedItems) Item1.SetBounds(Item1.Left + dx, Item1.Top + dy, Item1.Width, Item1.Height); modified = true; Invalidate(false); } } } void ItemResize_MouseDown(object sender, MouseEventArgs e) { //TODO: treshold isResizing = true; dragStartX = e.X; dragStartY = e.Y; } void ItemResize_MouseUp(object sender, MouseEventArgs e) { isResizing = false; } void ItemResize_MouseMove(object sender, MouseEventArgs e) { Control BaseItem = (sender as Control).Parent; if (isResizing) { //other items in selection? BaseItem.SetBounds(BaseItem.Left, BaseItem.Top, BaseItem.Width + e.X - dragStartX, BaseItem.Height + e.Y - dragStartY); modified = true; Invalidate(false); BaseItem.Invalidate(true); } } #endregion #region LinkPoints const int ConnectionWidth = 6; const int ConnectionHang = 50; protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); //for each connection linkpoint couple draw arc e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Pen p = new Pen(Color.Black, ConnectionWidth); Point h1; Point h2; foreach (LinkConnection lc in connections) { h1 = lc.LinkPoint1.PanelHotSpot; h2 = lc.LinkPoint2.PanelHotSpot; p.Color = lc.ConnectionColor; e.Graphics.DrawBezier(p, h1, new Point(h1.X, h1.Y + ConnectionHang), new Point(h2.X, h2.Y + ConnectionHang), h2); //TODO: width tension and hang as settings parameters } p.Dispose(); if (isSelecting) { p = new Pen(SystemColors.HighlightText, 1); p.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; Point[] ps = new Point[4]; ps[0] = new Point(dragStartX, dragStartY); ps[1] = new Point(dragStartX, dragSelectY); ps[2] = new Point(dragSelectX, dragSelectY); ps[3] = new Point(dragSelectX, dragStartY); e.Graphics.DrawPolygon(p, ps); p.Dispose(); } } private class ColorStockEntry { public Color Color; public int Count; public ColorStockEntry(Color c) { Color = c; Count = 0; } } static private ColorStockEntry[] ColorStock = { new ColorStockEntry(Color.Red), new ColorStockEntry(Color.Lime), new ColorStockEntry(Color.Blue), new ColorStockEntry(Color.Aqua), new ColorStockEntry(Color.Fuchsia), new ColorStockEntry(Color.Yellow), new ColorStockEntry(Color.Brown), new ColorStockEntry(Color.Navy), new ColorStockEntry(Color.DarkGray), new ColorStockEntry(Color.Orange), new ColorStockEntry(Color.SkyBlue), new ColorStockEntry(Color.Firebrick), new ColorStockEntry(Color.DarkBlue), new ColorStockEntry(Color.HotPink), new ColorStockEntry(Color.ForestGreen), new ColorStockEntry(Color.Cyan), new ColorStockEntry(Color.DarkRed), new ColorStockEntry(Color.CornflowerBlue), new ColorStockEntry(Color.Purple), new ColorStockEntry(Color.LightGreen), new ColorStockEntry(Color.Gold), new ColorStockEntry(Color.PaleTurquoise), new ColorStockEntry(Color.Crimson), new ColorStockEntry(Color.Teal), new ColorStockEntry(Color.SlateGray), new ColorStockEntry(Color.AliceBlue), new ColorStockEntry(Color.White), new ColorStockEntry(Color.LawnGreen), new ColorStockEntry(Color.Chocolate), new ColorStockEntry(Color.DodgerBlue), new ColorStockEntry(Color.PeachPuff), new ColorStockEntry(Color.Coral), new ColorStockEntry(Color.Khaki), new ColorStockEntry(Color.FloralWhite), new ColorStockEntry(Color.DarkOliveGreen), new ColorStockEntry(Color.Violet), new ColorStockEntry(Color.Wheat), new ColorStockEntry(Color.Maroon), new ColorStockEntry(Color.SpringGreen), new ColorStockEntry(Color.Orchid), new ColorStockEntry(Color.Lavender), new ColorStockEntry(Color.Aquamarine), new ColorStockEntry(Color.Olive), new ColorStockEntry(Color.SteelBlue), new ColorStockEntry(Color.BurlyWood), new ColorStockEntry(Color.SeaGreen), new ColorStockEntry(Color.PaleGreen), new ColorStockEntry(Color.PapayaWhip), new ColorStockEntry(Color.CadetBlue), new ColorStockEntry(Color.Chartreuse) }; private Color NextLinkColor = Color.Transparent; private bool ColorsEqual(Color c1, Color c2) { return c1.A == c2.A && c1.R == c2.R && c1.G == c2.G && c1.B == c2.B; } //called by linkpoints to report the link public void ReportLinkConnect(RELinkPoint LinkPoint1, RELinkPoint LinkPoint2) { Color c; if (NextLinkColor == Color.Transparent) { //get next color from stock ColorStockEntry ce1 = ColorStock[0]; foreach (ColorStockEntry ce in ColorStock) if (ce.Count < ce1.Count) ce1 = ce; c = ce1.Color; ce1.Count++; } else { c = NextLinkColor; NextLinkColor = Color.Transparent; foreach (ColorStockEntry ce in ColorStock) if (ColorsEqual(c, ce.Color)) { ce.Count++; break; } } connections.Add(new LinkConnection(LinkPoint1, LinkPoint2, c)); modified = true; Invalidate(false); LinkPoint1.Invalidate(false); LinkPoint2.Invalidate(false); } public void ReportLinkDisconnect(RELinkPoint LinkPoint) { LinkConnection lc = null; foreach (LinkConnection lc1 in connections) if (lc1.LinkPoint1 == LinkPoint || lc1.LinkPoint2 == LinkPoint) lc = lc1; if (lc != null) { //decrease count in color stock foreach(ColorStockEntry c in ColorStock) if (ColorsEqual(c.Color, lc.ConnectionColor)) { c.Count--; break; } connections.Remove(lc); //lc.LinkPointX.Connection=null;? modified = true; Invalidate(false); lc.LinkPoint1.Invalidate(false); lc.LinkPoint2.Invalidate(false); } } internal event LinkPointSignalEvent LinkPointSignal; public void ReportLinkSignal(RELinkPoint LinkPoint, RELinkPointSignalType Signal, object Data, bool MoreComing) { LinkPointSignal(LinkPoint, Signal, Data, MoreComing); } #endregion } internal class LinkConnection { RELinkPoint LP1; RELinkPoint LP2; Color FConColor; public LinkConnection(RELinkPoint LinkPoint1, RELinkPoint LinkPoint2, Color ConnectionColor) { LP1 = LinkPoint1; LP2 = LinkPoint2; FConColor = ConnectionColor; LP1.ConnectionColor = FConColor; LP2.ConnectionColor = FConColor; //assert LP1.Connection=LP2 && LP2.Connection=LP1 } public Color ConnectionColor { get { return FConColor; } } public RELinkPoint LinkPoint1 { get { return LP1; } } public RELinkPoint LinkPoint2 { get { return LP2; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member namespace Thinktecture.Relay.OnPremiseConnector.IdentityModel { public class OAuth2Client { private readonly HttpClient _client; private readonly ClientAuthenticationStyle _authenticationStyle; private readonly Uri _address; private readonly string _clientId; private readonly string _clientSecret; public enum ClientAuthenticationStyle { BasicAuthentication, PostValues, None, } public OAuth2Client(Uri address) : this(address, new HttpClientHandler()) { } public OAuth2Client(Uri address, HttpMessageHandler innerHttpClientHandler) { if (innerHttpClientHandler == null) { throw new ArgumentNullException(nameof(innerHttpClientHandler)); } _client = new HttpClient(innerHttpClientHandler) { BaseAddress = address, }; _address = address; _authenticationStyle = ClientAuthenticationStyle.None; } public OAuth2Client(Uri address, string clientId, string clientSecret, ClientAuthenticationStyle style = ClientAuthenticationStyle.BasicAuthentication) : this(address, clientId, clientSecret, new HttpClientHandler(), style) { } public OAuth2Client(Uri address, string clientId, string clientSecret, HttpMessageHandler innerHttpClientHandler, ClientAuthenticationStyle style = ClientAuthenticationStyle.BasicAuthentication) : this(address, innerHttpClientHandler) { if (style == ClientAuthenticationStyle.BasicAuthentication) { _client.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(clientId, clientSecret); } else if (style == ClientAuthenticationStyle.PostValues) { _authenticationStyle = style; _clientId = clientId; _clientSecret = clientSecret; } } public TimeSpan Timeout { set => _client.Timeout = value; } public string CreateCodeFlowUrl(string clientId, string scope = null, string redirectUri = null, string state = null, string nonce = null, string loginHint = null, string acrValues = null, Dictionary<string, string> additionalValues = null) { return CreateAuthorizeUrl(clientId, OAuth2Constants.ResponseTypes.Code, scope, redirectUri, state, nonce, loginHint, acrValues, additionalValues: additionalValues); } public string CreateImplicitFlowUrl(string clientId, string scope = null, string redirectUri = null, string state = null, string nonce = null, string loginHint = null, string acrValues = null, Dictionary<string, string> additionalValues = null) { return CreateAuthorizeUrl(clientId, OAuth2Constants.ResponseTypes.Token, scope, redirectUri, state, nonce, loginHint, acrValues, additionalValues: additionalValues); } public string CreateAuthorizeUrl(string clientId, string responseType, string scope = null, string redirectUri = null, string state = null, string nonce = null, string loginHint = null, string acrValues = null, string responseMode = null, Dictionary<string, string> additionalValues = null) { var values = new Dictionary<string, string> { { OAuth2Constants.ClientId, clientId }, { OAuth2Constants.ResponseType, responseType } }; if (!string.IsNullOrWhiteSpace(scope)) { values.Add(OAuth2Constants.Scope, scope); } if (!string.IsNullOrWhiteSpace(redirectUri)) { values.Add(OAuth2Constants.RedirectUri, redirectUri); } if (!string.IsNullOrWhiteSpace(state)) { values.Add(OAuth2Constants.State, state); } if (!string.IsNullOrWhiteSpace(nonce)) { values.Add(OAuth2Constants.Nonce, nonce); } if (!string.IsNullOrWhiteSpace(loginHint)) { values.Add(OAuth2Constants.LoginHint, loginHint); } if (!string.IsNullOrWhiteSpace(acrValues)) { values.Add(OAuth2Constants.AcrValues, acrValues); } if (!string.IsNullOrWhiteSpace(responseMode)) { values.Add(OAuth2Constants.ResponseMode, responseMode); } return CreateAuthorizeUrl(_address, Merge(values, additionalValues)); } public static string CreateAuthorizeUrl(Uri endpoint, Dictionary<string, string> values) { var qs = string.Join("&", values.Select(kvp => String.Format("{0}={1}", WebUtility.UrlEncode(kvp.Key), WebUtility.UrlEncode(kvp.Value))).ToArray()); return string.Format("{0}?{1}", endpoint.AbsoluteUri, qs); } public Task<TokenResponse> RequestResourceOwnerPasswordAsync(string userName, string password, string scope = null, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.Password }, { OAuth2Constants.UserName, userName }, { OAuth2Constants.Password, password } }; if (!string.IsNullOrWhiteSpace(scope)) { fields.Add(OAuth2Constants.Scope, scope); } return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public Task<TokenResponse> RequestAuthorizationCodeAsync(string code, string redirectUri, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.AuthorizationCode }, { OAuth2Constants.Code, code }, { OAuth2Constants.RedirectUri, redirectUri } }; return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public Task<TokenResponse> RequestRefreshTokenAsync(string refreshToken, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.RefreshToken }, { OAuth2Constants.RefreshToken, refreshToken } }; return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public Task<TokenResponse> RequestClientCredentialsAsync(string scope = null, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, OAuth2Constants.GrantTypes.ClientCredentials } }; if (!string.IsNullOrWhiteSpace(scope)) { fields.Add(OAuth2Constants.Scope, scope); } return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public Task<TokenResponse> RequestCustomGrantAsync(string grantType, string scope = null, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, grantType } }; if (!string.IsNullOrWhiteSpace(scope)) { fields.Add(OAuth2Constants.Scope, scope); } return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public Task<TokenResponse> RequestCustomAsync(Dictionary<string, string> values, CancellationToken cancellationToken = default(CancellationToken)) { return RequestAsync(Merge(values), cancellationToken); } public Task<TokenResponse> RequestAssertionAsync(string assertionType, string assertion, string scope = null, Dictionary<string, string> additionalValues = null, CancellationToken cancellationToken = default(CancellationToken)) { var fields = new Dictionary<string, string> { { OAuth2Constants.GrantType, assertionType }, { OAuth2Constants.Assertion, assertion }, }; if (!string.IsNullOrWhiteSpace(scope)) { fields.Add(OAuth2Constants.Scope, scope); } return RequestAsync(Merge(fields, additionalValues), cancellationToken); } public async Task<TokenResponse> RequestAsync(Dictionary<string, string> form, CancellationToken cancellationToken = default(CancellationToken)) { var response = await _client.PostAsync(string.Empty, new FormUrlEncodedContent(form), cancellationToken).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest) { var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return new TokenResponse(content); } return new TokenResponse(response.StatusCode, response.ReasonPhrase); } private Dictionary<string, string> Merge(Dictionary<string, string> explicitValues, Dictionary<string, string> additionalValues = null) { var merged = explicitValues; if (_authenticationStyle == ClientAuthenticationStyle.PostValues) { merged.Add(OAuth2Constants.ClientId, _clientId); merged.Add(OAuth2Constants.ClientSecret, _clientSecret); } if (additionalValues != null) { merged = explicitValues.Concat(additionalValues.Where(add => !explicitValues.ContainsKey(add.Key))) .ToDictionary(final => final.Key, final => final.Value); } return merged; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading.Tasks; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("WorkItemGroup Name={Name} State={state}")] internal class WorkItemGroup : IWorkItem { private enum WorkGroupStatus { Waiting = 0, Runnable = 1, Running = 2, Shutdown = 3 } private static readonly TraceLogger appLogger = TraceLogger.GetLogger("Scheduler.WorkItemGroup", TraceLogger.LoggerType.Runtime); private readonly TraceLogger log; private readonly OrleansTaskScheduler masterScheduler; private WorkGroupStatus state; private readonly Object lockable; private readonly Queue<Task> workItems; private long totalItemsEnQueued; // equals total items queued, + 1 private long totalItemsProcessed; private readonly QueueTrackingStatistic queueTracking; private TimeSpan totalQueuingDelay; private readonly long quantumExpirations; private readonly int workItemGroupStatisticsNumber; internal ActivationTaskScheduler TaskRunner { get; private set; } public DateTime TimeQueued { get; set; } public TimeSpan TimeSinceQueued { get { return Utils.Since(TimeQueued); } } public ISchedulingContext SchedulingContext { get; set; } public bool IsSystemPriority { get { return SchedulingUtils.IsSystemPriorityContext(SchedulingContext); } } internal bool IsSystemGroup { get { return SchedulingUtils.IsSystemContext(SchedulingContext); } } public string Name { get { return SchedulingContext == null ? "unknown" : SchedulingContext.Name; } } internal int ExternalWorkItemCount { get { lock (lockable) { return WorkItemCount; } } } private int WorkItemCount { get { return workItems.Count; } } internal float AverageQueueLenght { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.AverageQueueLength; } #endif return 0; } } internal float NumEnqueuedRequests { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.NumEnqueuedRequests; } #endif return 0; } } internal float ArrivalRate { get { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) { return queueTracking.ArrivalRate; } #endif return 0; } } private bool IsActive { get { return WorkItemCount != 0; } } // This is the maximum number of work items to be processed in an activation turn. // If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing). private const int MaxWorkItemsPerTurn = 0; // Unlimited // This is a soft time limit on the duration of activation macro-turn (a number of micro-turns). // If a activation was running its micro-turns longer than this, we will give up the thread. // If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). public static TimeSpan ActivationSchedulingQuantum { get; set; } // This is the maximum number of waiting threads (blocked in WaitForResponse) allowed // per ActivationWorker. An attempt to wait when there are already too many threads waiting // will result in a TooManyWaitersException being thrown. //private static readonly int MaxWaitingThreads = 500; internal WorkItemGroup(OrleansTaskScheduler sched, ISchedulingContext schedulingContext) { masterScheduler = sched; SchedulingContext = schedulingContext; state = WorkGroupStatus.Waiting; workItems = new Queue<Task>(); lockable = new Object(); totalItemsEnQueued = 0; totalItemsProcessed = 0; totalQueuingDelay = TimeSpan.Zero; quantumExpirations = 0; TaskRunner = new ActivationTaskScheduler(this); log = IsSystemPriority ? TraceLogger.GetLogger("Scheduler." + Name + ".WorkItemGroup", TraceLogger.LoggerType.Runtime) : appLogger; if (StatisticsCollector.CollectShedulerQueuesStats) { queueTracking = new QueueTrackingStatistic("Scheduler." + SchedulingContext.Name); queueTracking.OnStartExecution(); } if (StatisticsCollector.CollectPerWorkItemStats) { workItemGroupStatisticsNumber = SchedulerStatisticsGroup.RegisterWorkItemGroup(SchedulingContext.Name, SchedulingContext, () => { var sb = new StringBuilder(); lock (lockable) { sb.Append("QueueLength = " + WorkItemCount); sb.Append(String.Format(", State = {0}", state)); if (state == WorkGroupStatus.Runnable) sb.Append(String.Format("; oldest item is {0} old", workItems.Count >= 0 ? workItems.Peek().ToString() : "null")); } return sb.ToString(); }); } } /// <summary> /// Adds a task to this activation. /// If we're adding it to the run list and we used to be waiting, now we're runnable. /// </summary> /// <param name="task">The work item to add.</param> public void EnqueueTask(Task task) { lock (lockable) { #if DEBUG if (log.IsVerbose2) log.Verbose2("EnqueueWorkItem {0} into {1} when TaskScheduler.Current={2}", task, SchedulingContext, TaskScheduler.Current); #endif if (state == WorkGroupStatus.Shutdown) { ReportWorkGroupProblem( String.Format("Enqueuing task {0} to a stopped work item group. Going to ignore and not execute it. " + "The likely reason is that the task is not being 'awaited' properly.", task), ErrorCode.SchedulerNotEnqueuWorkWhenShutdown); task.Ignore(); // Ignore this Task, so in case it is faulted it will not cause UnobservedException. return; } long thisSequenceNumber = totalItemsEnQueued++; int count = WorkItemCount; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectShedulerQueuesStats) queueTracking.OnEnQueueRequest(1, count); if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemEnqueue(); #endif workItems.Enqueue(task); int maxPendingItemsLimit = masterScheduler.MaxPendingItemsLimit.SoftLimitThreshold; if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit) { log.Warn(ErrorCode.SchedulerTooManyPendingItems, String.Format("{0} pending work items for group {1}, exceeding the warning threshold of {2}", count, Name, maxPendingItemsLimit)); } if (state != WorkGroupStatus.Waiting) return; state = WorkGroupStatus.Runnable; #if DEBUG if (log.IsVerbose3) log.Verbose3("Add to RunQueue {0}, #{1}, onto {2}", task, thisSequenceNumber, SchedulingContext); #endif masterScheduler.RunQueue.Add(this); } } /// <summary> /// Shuts down this work item group so that it will not process any additional work items, even if they /// have already been queued. /// </summary> internal void Stop() { lock (lockable) { if (IsActive) { ReportWorkGroupProblem( String.Format("WorkItemGroup is being stoped while still active. workItemCount = {0}." + "The likely reason is that the task is not being 'awaited' properly.", WorkItemCount), ErrorCode.SchedulerWorkGroupStopping); } if (state == WorkGroupStatus.Shutdown) { log.Warn(ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {0}", this.ToString()); return; } state = WorkGroupStatus.Shutdown; if (StatisticsCollector.CollectPerWorkItemStats) SchedulerStatisticsGroup.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber); if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemDrop(WorkItemCount); if (StatisticsCollector.CollectShedulerQueuesStats) queueTracking.OnStopExecution(); foreach (Task task in workItems) { // Ignore all queued Tasks, so in case they are faulted they will not cause UnobservedException. task.Ignore(); } workItems.Clear(); } } #region IWorkItem Members public WorkItemType ItemType { get { return WorkItemType.WorkItemGroup; } } // Execute one or more turns for this activation. // This method is always called in a single-threaded environment -- that is, no more than one // thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc. public void Execute() { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (!IsActive) return; // Don't mind if no work has been queued to this work group yet. ReportWorkGroupProblemWithBacktrace( "Cannot execute work items in a work item group that is in a shutdown state.", ErrorCode.SchedulerNotExecuteWhenShutdown); // Throws InvalidOperationException return; } state = WorkGroupStatus.Running; } var thread = WorkerPoolThread.CurrentWorkerThread; try { // Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation int count = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); do { lock (lockable) { if (state == WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) log.Warn(ErrorCode.SchedulerSkipWorkStopping, "Thread {0} is exiting work loop due to Shutdown state {1} while still having {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); else if(log.IsVerbose) log.Verbose("Thread {0} is exiting work loop due to Shutdown state {1}. Has {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } // Check the cancellation token (means that the silo is stopping) if (thread.CancelToken.IsCancellationRequested) { log.Warn(ErrorCode.SchedulerSkipWorkCancelled, "Thread {0} is exiting work loop due to cancellation token. WorkItemGroup: {1}, Have {2} work items in the queue.", thread.ToString(), this.ToString(), WorkItemCount); break; } } // Get the first Work Item on the list Task task; lock (lockable) { if (workItems.Count > 0) task = workItems.Dequeue(); else // If the list is empty, then we're done break; } #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectGlobalShedulerStats) SchedulerStatisticsGroup.OnWorkItemDequeue(); #endif #if DEBUG if (log.IsVerbose2) log.Verbose2("About to execute task {0} in SchedulingContext={1}", task, SchedulingContext); #endif var taskStart = stopwatch.Elapsed; try { thread.CurrentTask = task; #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) SchedulerStatisticsGroup.OnTurnExecutionStartsByWorkGroup(workItemGroupStatisticsNumber, thread.WorkerThreadStatisticsNumber, SchedulingContext); #endif TaskRunner.RunTask(task); } catch (Exception ex) { log.Error(ErrorCode.SchedulerExceptionFromExecute, String.Format("Worker thread caught an exception thrown from Execute by task {0}", task), ex); throw; } finally { #if TRACK_DETAILED_STATS if (StatisticsCollector.CollectTurnsStats) SchedulerStatisticsGroup.OnTurnExecutionEnd(Utils.Since(thread.CurrentStateStarted)); if (StatisticsCollector.CollectThreadTimeTrackingStats) thread.threadTracking.IncrementNumberOfProcessed(); #endif totalItemsProcessed++; var taskLength = stopwatch.Elapsed - taskStart; if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold) { SchedulerStatisticsGroup.NumLongRunningTurns.Increment(); log.Warn(ErrorCode.SchedulerTurnTooLong3, "Task {0} in WorkGroup {1} took elapsed time {2:g} for execution, which is longer than {3}. Running on thread {4}", OrleansTaskExtentions.ToString(task), SchedulingContext.ToString(), taskLength, OrleansTaskScheduler.TurnWarningLengthThreshold, thread.ToString()); } thread.CurrentTask = null; } count++; } while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) && ((ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < ActivationSchedulingQuantum))); stopwatch.Stop(); } catch (Exception ex) { log.Error(ErrorCode.Runtime_Error_100032, String.Format("Worker thread {0} caught an exception thrown from IWorkItem.Execute", thread), ex); } finally { // Now we're not Running anymore. // If we left work items on our run list, we're Runnable, and need to go back on the silo run queue; // If our run list is empty, then we're waiting. lock (lockable) { if (state != WorkGroupStatus.Shutdown) { if (WorkItemCount > 0) { state = WorkGroupStatus.Runnable; masterScheduler.RunQueue.Add(this); } else { state = WorkGroupStatus.Waiting; } } } } } #endregion public override string ToString() { return String.Format("{0}WorkItemGroup:Name={1},WorkGroupStatus={2}", IsSystemGroup ? "System*" : "", Name, state); } public string DumpStatus() { lock (lockable) { var sb = new StringBuilder(); sb.Append(this); sb.AppendFormat(". Currently QueuedWorkItems={0}; Total EnQueued={1}; Total processed={2}; Quantum expirations={3}; ", WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations); if (AverageQueueLenght > 0) { sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLenght); if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0) { sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds); } } sb.AppendFormat("TaskRunner={0}; ", TaskRunner); if (SchedulingContext != null) { sb.AppendFormat("Detailed SchedulingContext=<{0}>", SchedulingContext.DetailedStatus()); } return sb.ToString(); } } private void ReportWorkGroupProblemWithBacktrace(string what, ErrorCode errorCode) { var st = new StackTrace(); var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg + Environment.NewLine + " Called from " + st); } private void ReportWorkGroupProblem(string what, ErrorCode errorCode) { var msg = string.Format("{0} {1}", what, DumpStatus()); log.Warn(errorCode, msg); } } }
// 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.Runtime.InteropServices; using System.Security; namespace System.DirectoryServices.Protocols { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal class Luid { private int _lowPart; private int _highPart; public int LowPart => _lowPart; public int HighPart => _highPart; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class SEC_WINNT_AUTH_IDENTITY_EX { public int version; public int length; public string user; public int userLength; public string domain; public int domainLength; public string password; public int passwordLength; public int flags; public string packageList; public int packageListLength; } internal enum BindMethod : uint { LDAP_AUTH_OTHERKIND = 0x86, LDAP_AUTH_SICILY = LDAP_AUTH_OTHERKIND | 0x0200, LDAP_AUTH_MSN = LDAP_AUTH_OTHERKIND | 0x0800, LDAP_AUTH_NTLM = LDAP_AUTH_OTHERKIND | 0x1000, LDAP_AUTH_DPA = LDAP_AUTH_OTHERKIND | 0x2000, LDAP_AUTH_NEGOTIATE = LDAP_AUTH_OTHERKIND | 0x0400, LDAP_AUTH_SSPI = LDAP_AUTH_NEGOTIATE, LDAP_AUTH_DIGEST = LDAP_AUTH_OTHERKIND | 0x4000, LDAP_AUTH_EXTERNAL = LDAP_AUTH_OTHERKIND | 0x0020 } internal enum LdapOption { LDAP_OPT_DESC = 0x01, LDAP_OPT_DEREF = 0x02, LDAP_OPT_SIZELIMIT = 0x03, LDAP_OPT_TIMELIMIT = 0x04, LDAP_OPT_REFERRALS = 0x08, LDAP_OPT_RESTART = 0x09, LDAP_OPT_SSL = 0x0a, LDAP_OPT_REFERRAL_HOP_LIMIT = 0x10, LDAP_OPT_VERSION = 0x11, LDAP_OPT_API_FEATURE_INFO = 0x15, LDAP_OPT_HOST_NAME = 0x30, LDAP_OPT_ERROR_NUMBER = 0x31, LDAP_OPT_ERROR_STRING = 0x32, LDAP_OPT_SERVER_ERROR = 0x33, LDAP_OPT_SERVER_EXT_ERROR = 0x34, LDAP_OPT_HOST_REACHABLE = 0x3E, LDAP_OPT_PING_KEEP_ALIVE = 0x36, LDAP_OPT_PING_WAIT_TIME = 0x37, LDAP_OPT_PING_LIMIT = 0x38, LDAP_OPT_DNSDOMAIN_NAME = 0x3B, LDAP_OPT_GETDSNAME_FLAGS = 0x3D, LDAP_OPT_PROMPT_CREDENTIALS = 0x3F, LDAP_OPT_TCP_KEEPALIVE = 0x40, LDAP_OPT_FAST_CONCURRENT_BIND = 0x41, LDAP_OPT_SEND_TIMEOUT = 0x42, LDAP_OPT_REFERRAL_CALLBACK = 0x70, LDAP_OPT_CLIENT_CERTIFICATE = 0x80, LDAP_OPT_SERVER_CERTIFICATE = 0x81, LDAP_OPT_AUTO_RECONNECT = 0x91, LDAP_OPT_SSPI_FLAGS = 0x92, LDAP_OPT_SSL_INFO = 0x93, LDAP_OPT_SIGN = 0x95, LDAP_OPT_ENCRYPT = 0x96, LDAP_OPT_SASL_METHOD = 0x97, LDAP_OPT_AREC_EXCLUSIVE = 0x98, LDAP_OPT_SECURITY_CONTEXT = 0x99, LDAP_OPT_ROOTDSE_CACHE = 0x9a } internal enum ResultAll { LDAP_MSG_ALL = 1, LDAP_MSG_RECEIVED = 2, LDAP_MSG_POLLINGALL = 3 } [StructLayout(LayoutKind.Sequential)] internal sealed class LDAP_TIMEVAL { public int tv_sec; public int tv_usec; } [StructLayout(LayoutKind.Sequential)] internal sealed class berval { public int bv_len = 0; public IntPtr bv_val = IntPtr.Zero; public berval() { } } [StructLayout(LayoutKind.Sequential)] internal sealed class SafeBerval { public int bv_len = 0; public IntPtr bv_val = IntPtr.Zero; ~SafeBerval() { if (bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(bv_val); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class LdapControl { public IntPtr ldctl_oid = IntPtr.Zero; public berval ldctl_value = null; public bool ldctl_iscritical = false; public LdapControl() { } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LdapReferralCallback { public int sizeofcallback; public QUERYFORCONNECTIONInternal query; public NOTIFYOFNEWCONNECTIONInternal notify; public DEREFERENCECONNECTIONInternal dereference; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct CRYPTOAPI_BLOB { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct SecPkgContext_IssuerListInfoEx { public IntPtr aIssuers; public int cIssuers; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal sealed class LdapMod { public int type = 0; public IntPtr attribute = IntPtr.Zero; public IntPtr values = IntPtr.Zero; ~LdapMod() { if (attribute != IntPtr.Zero) { Marshal.FreeHGlobal(attribute); } if (values != IntPtr.Zero) { Marshal.FreeHGlobal(values); } } } internal class Wldap32 { private const string Wldap32dll = "wldap32.dll"; public const int SEC_WINNT_AUTH_IDENTITY_UNICODE = 0x2; public const int SEC_WINNT_AUTH_IDENTITY_VERSION = 0x200; public const string MICROSOFT_KERBEROS_NAME_W = "Kerberos"; [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_bind_sW", CharSet = CharSet.Unicode)] public static extern int ldap_bind_s([In]ConnectionHandle ldapHandle, string dn, SEC_WINNT_AUTH_IDENTITY_EX credentials, BindMethod method); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_initW", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr ldap_init(string hostName, int portNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_connect", CharSet = CharSet.Unicode)] public static extern int ldap_connect([In] ConnectionHandle ldapHandle, LDAP_TIMEVAL timeout); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, EntryPoint = "ldap_unbind", CharSet = CharSet.Unicode)] public static extern int ldap_unbind([In] IntPtr ldapHandle); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_get_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_set_option_int([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref int inValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_get_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_set_option_ptr([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref IntPtr inValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_get_option_sechandle([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref SecurityHandle outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_get_option_secInfo([In] ConnectionHandle ldapHandle, [In] LdapOption option, [In, Out] SecurityPackageContextConnectionInformation outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_set_option_referral([In] ConnectionHandle ldapHandle, [In] LdapOption option, ref LdapReferralCallback outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_set_option_clientcert([In] ConnectionHandle ldapHandle, [In] LdapOption option, QUERYCLIENTCERT outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_set_optionW", CharSet = CharSet.Unicode)] public static extern int ldap_set_option_servercert([In] ConnectionHandle ldapHandle, [In] LdapOption option, VERIFYSERVERCERT outValue); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "LdapGetLastError")] public static extern int LdapGetLastError(); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "cldap_openW", SetLastError = true, CharSet = CharSet.Unicode)] public static extern IntPtr cldap_open(string hostName, int portNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_simple_bind_sW", CharSet = CharSet.Unicode)] public static extern int ldap_simple_bind_s([In] ConnectionHandle ldapHandle, string distinguishedName, string password); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_delete_extW", CharSet = CharSet.Unicode)] public static extern int ldap_delete_ext([In] ConnectionHandle ldapHandle, string dn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result", SetLastError = true, CharSet = CharSet.Unicode)] public static extern int ldap_result([In] ConnectionHandle ldapHandle, int messageId, int all, LDAP_TIMEVAL timeout, ref IntPtr Mesage); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)] public static extern int ldap_parse_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref int serverError, ref IntPtr dn, ref IntPtr message, ref IntPtr referral, ref IntPtr control, byte freeIt); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_resultW", CharSet = CharSet.Unicode)] public static extern int ldap_parse_result_referral([In] ConnectionHandle ldapHandle, [In] IntPtr result, IntPtr serverError, IntPtr dn, IntPtr message, ref IntPtr referral, IntPtr control, byte freeIt); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_memfreeW", CharSet = CharSet.Unicode)] public static extern void ldap_memfree([In] IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_freeW", CharSet = CharSet.Unicode)] public static extern int ldap_value_free([In] IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_controls_freeW", CharSet = CharSet.Unicode)] public static extern int ldap_controls_free([In] IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_abandon", CharSet = CharSet.Unicode)] public static extern int ldap_abandon([In] ConnectionHandle ldapHandle, [In] int messagId); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_start_tls_sW", CharSet = CharSet.Unicode)] public static extern int ldap_start_tls(ConnectionHandle ldapHandle, ref int ServerReturnValue, ref IntPtr Message, IntPtr ServerControls, IntPtr ClientControls); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_stop_tls_s", CharSet = CharSet.Unicode)] public static extern byte ldap_stop_tls(ConnectionHandle ldapHandle); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_rename_extW", CharSet = CharSet.Unicode)] public static extern int ldap_rename([In] ConnectionHandle ldapHandle, string dn, string newRdn, string newParentDn, int deleteOldRdn, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_compare_extW", CharSet = CharSet.Unicode)] public static extern int ldap_compare([In] ConnectionHandle ldapHandle, string dn, string attributeName, string strValue, berval binaryValue, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_add_extW", CharSet = CharSet.Unicode)] public static extern int ldap_add([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_modify_extW", CharSet = CharSet.Unicode)] public static extern int ldap_modify([In] ConnectionHandle ldapHandle, string dn, IntPtr attrs, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_extended_operationW", CharSet = CharSet.Unicode)] public static extern int ldap_extended_operation([In] ConnectionHandle ldapHandle, string oid, berval data, IntPtr servercontrol, IntPtr clientcontrol, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_extended_resultW", CharSet = CharSet.Unicode)] public static extern int ldap_parse_extended_result([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr oid, ref IntPtr data, byte freeIt); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_msgfree", CharSet = CharSet.Unicode)] public static extern int ldap_msgfree([In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_search_extW", CharSet = CharSet.Unicode)] public static extern int ldap_search([In] ConnectionHandle ldapHandle, string dn, int scope, string filter, IntPtr attributes, bool attributeOnly, IntPtr servercontrol, IntPtr clientcontrol, int timelimit, int sizelimit, ref int messageNumber); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_entry", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_first_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_entry", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_next_entry([In] ConnectionHandle ldapHandle, [In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_reference", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_first_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_reference", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_next_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_dnW", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_get_dn([In] ConnectionHandle ldapHandle, [In] IntPtr result); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_first_attributeW", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_first_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr address); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_next_attributeW", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_next_attribute([In] ConnectionHandle ldapHandle, [In] IntPtr result, [In, Out] IntPtr address); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_free", CharSet = CharSet.Unicode)] public static extern IntPtr ber_free([In] IntPtr berelement, int option); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_get_values_lenW", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_get_values_len([In] ConnectionHandle ldapHandle, [In] IntPtr result, string name); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_value_free_len", CharSet = CharSet.Unicode)] public static extern IntPtr ldap_value_free_len([In] IntPtr berelement); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_parse_referenceW", CharSet = CharSet.Unicode)] public static extern int ldap_parse_reference([In] ConnectionHandle ldapHandle, [In] IntPtr result, ref IntPtr referrals); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_alloc_t", CharSet = CharSet.Unicode)] public static extern IntPtr ber_alloc(int option); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)] public static extern int ber_printf_emptyarg(BerSafeHandle berElement, string format); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)] public static extern int ber_printf_int(BerSafeHandle berElement, string format, int value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)] public static extern int ber_printf_bytearray(BerSafeHandle berElement, string format, HGlobalMemHandle value, int length); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_printf", CharSet = CharSet.Unicode)] public static extern int ber_printf_berarray(BerSafeHandle berElement, string format, IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_flatten", CharSet = CharSet.Unicode)] public static extern int ber_flatten(BerSafeHandle berElement, ref IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_init", CharSet = CharSet.Unicode)] public static extern IntPtr ber_init(berval value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)] public static extern int ber_scanf(BerSafeHandle berElement, string format); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)] public static extern int ber_scanf_int(BerSafeHandle berElement, string format, ref int value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)] public static extern int ber_scanf_ptr(BerSafeHandle berElement, string format, ref IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_scanf", CharSet = CharSet.Unicode)] public static extern int ber_scanf_bitstring(BerSafeHandle berElement, string format, ref IntPtr value, ref int length); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvfree", CharSet = CharSet.Unicode)] public static extern int ber_bvfree(IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ber_bvecfree", CharSet = CharSet.Unicode)] public static extern int ber_bvecfree(IntPtr value); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_create_sort_controlW", CharSet = CharSet.Unicode)] public static extern int ldap_create_sort_control(ConnectionHandle handle, IntPtr keys, byte critical, ref IntPtr control); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_control_freeW", CharSet = CharSet.Unicode)] public static extern int ldap_control_free(IntPtr control); [DllImport("Crypt32.dll", EntryPoint = "CertFreeCRLContext", CharSet = CharSet.Unicode)] public static extern int CertFreeCRLContext(IntPtr certContext); [DllImport(Wldap32dll, CallingConvention = CallingConvention.Cdecl, EntryPoint = "ldap_result2error", CharSet = CharSet.Unicode)] public static extern int ldap_result2error([In] ConnectionHandle ldapHandle, [In] IntPtr result, int freeIt); } }
// 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 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)); } }
#pragma warning disable 1587 #region Header /// /// JsonReader.cs /// Stream-like access to JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ThirdParty.Json.LitJson { internal enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, UInt, Long, ULong, Double, String, Boolean, Null } internal class JsonReader { #region Fields private Stack<JsonToken> depth = new Stack<JsonToken>(); private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; lexer = new Lexer (reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } #endregion #region Private Methods private void ProcessNumber (string number) { if (number.IndexOf ('.') != -1 || number.IndexOf ('e') != -1 || number.IndexOf ('E') != -1) { double n_double; if (Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } uint n_uint32; if (UInt32.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_uint32)) { token = JsonToken.UInt; token_value = n_uint32; return; } long n_int64; if (Int64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } ulong n_uint64; if (UInt64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_uint64)) { token = JsonToken.ULong; token_value = n_uint64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.ULong; token_value = default(ulong); } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } #endregion public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; reader = null; } public bool Read() { if (end_of_input) return false; if (end_of_json) { end_of_json = false; } token = JsonToken.None; parser_in_string = false; parser_return = false; // Check if the first read call. If so then do an extra ReadToken because Read assumes that the previous // call to Read has already called ReadToken. if (!read_started) { read_started = true; if (!ReadToken()) return false; } do { current_symbol = current_input; ProcessSymbol(); if (parser_return) { if (this.token == JsonToken.ObjectStart || this.token == JsonToken.ArrayStart) { depth.Push(this.token); } else if (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd) { // Clear out property name if is on top. This could happen if the value for the property was null. if (depth.Peek() == JsonToken.PropertyName) depth.Pop(); // Pop the opening token for this closing token. Make sure it is of the right type otherwise // the document is invalid. var opening = depth.Pop(); if (this.token == JsonToken.ObjectEnd && opening != JsonToken.ObjectStart) throw new JsonException("Error: Current token is ObjectEnd which does not match the opening " + opening.ToString()); if (this.token == JsonToken.ArrayEnd && opening != JsonToken.ArrayStart) throw new JsonException("Error: Current token is ArrayEnd which does not match the opening " + opening.ToString()); // If that last element is popped then we reached the end of the JSON object. if (depth.Count == 0) { end_of_json = true; } } // If the top of the stack is an object start and the next read is a string then it must be a property name // to add to the stack. else if (depth.Count > 0 && depth.Peek() != JsonToken.PropertyName && this.token == JsonToken.String && depth.Peek() == JsonToken.ObjectStart) { this.token = JsonToken.PropertyName; depth.Push(this.token); } if ( (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd || this.token == JsonToken.String || this.token == JsonToken.Boolean || this.token == JsonToken.Double || this.token == JsonToken.Int || this.token == JsonToken.UInt || this.token == JsonToken.Long || this.token == JsonToken.ULong || this.token == JsonToken.Null || this.token == JsonToken.String )) { // If we found a value but we are not in an array or object then the document is an invalid json document. if (depth.Count == 0) { if (this.token != JsonToken.ArrayEnd && this.token != JsonToken.ObjectEnd) { throw new JsonException("Value without enclosing object or array"); } } // The valud of the property has been processed so pop the property name from the stack. else if (depth.Peek() == JsonToken.PropertyName) { depth.Pop(); } } // Read the next token that will be processed the next time the Read method is called. // This is done ahead of the next read so we can detect if we are at the end of the json document. // Otherwise EndOfInput would not return true until an attempt to read was made. if (!ReadToken() && depth.Count != 0) throw new JsonException("Incomplete JSON Document"); return true; } } while (ReadToken()); // If we reached the end of the document but there is still elements left in the depth stack then // the document is invalid JSON. if (depth.Count != 0) throw new JsonException("Incomplete JSON Document"); end_of_input = true; return false; } } }
//------------------------------------------------------------------------------ // <copyright file="BlobAsyncCopyController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.DataMovement; /// <summary> /// Blob asynchronous copy. /// </summary> internal class BlobAsyncCopyController : AsyncCopyController { private AzureBlobLocation destLocation; private CloudBlob destBlob; public BlobAsyncCopyController( TransferScheduler transferScheduler, TransferJob transferJob, CancellationToken cancellationToken) : base(transferScheduler, transferJob, cancellationToken) { this.destLocation = transferJob.Destination as AzureBlobLocation; CloudBlob transferDestBlob = this.destLocation.Blob; if (null == transferDestBlob) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ParameterCannotBeNullException, "Dest.Blob"), "transferJob"); } if (transferDestBlob.IsSnapshot) { throw new ArgumentException(Resources.DestinationMustBeBaseBlob, "transferJob"); } AzureBlobLocation sourceBlobLocation = transferJob.Source as AzureBlobLocation; if (sourceBlobLocation != null) { if (sourceBlobLocation.Blob.BlobType != transferDestBlob.BlobType) { throw new ArgumentException(Resources.SourceAndDestinationBlobTypeDifferent, "transferJob"); } if (StorageExtensions.Equals(sourceBlobLocation.Blob, transferDestBlob)) { throw new InvalidOperationException(Resources.SourceAndDestinationLocationCannotBeEqualException); } } this.destBlob = transferDestBlob; } protected override Uri DestUri { get { return this.destBlob.Uri; } } protected override Task DoFetchDestAttributesAsync() { AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( this.destLocation.AccessCondition, this.destLocation.CheckedAccessCondition); return this.destBlob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } protected override Task<string> DoStartCopyAsync() { AccessCondition destAccessCondition = Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition); if (null != this.SourceUri) { return this.destBlob.StartCopyAsync( this.SourceUri, null, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } else if (null != this.SourceBlob) { AccessCondition sourceAccessCondition = AccessCondition.GenerateIfMatchCondition(this.SourceBlob.Properties.ETag); return this.destBlob.StartCopyAsync( this.SourceBlob.GenerateCopySourceUri(), sourceAccessCondition, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } else { if (BlobType.BlockBlob == this.destBlob.BlobType) { return (this.destBlob as CloudBlockBlob).StartCopyAsync( this.SourceFile.GenerateCopySourceFile(), null, destAccessCondition, Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } else if (BlobType.PageBlob == this.destBlob.BlobType) { throw new InvalidOperationException(Resources.AsyncCopyFromFileToPageBlobNotSupportException); } else if (BlobType.AppendBlob == this.destBlob.BlobType) { throw new InvalidOperationException(Resources.AsyncCopyFromFileToAppendBlobNotSupportException); } else { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, Resources.NotSupportedBlobType, this.destBlob.BlobType)); } } } protected override void DoHandleGetDestinationException(StorageException se) { if (null != se) { if (0 == string.Compare(se.Message, Constants.BlobTypeMismatch, StringComparison.OrdinalIgnoreCase)) { // Current use error message to decide whether it caused by blob type mismatch, // We should ask xscl to expose an error code for this.. // Opened workitem 1487579 to track this. throw new InvalidOperationException(Resources.DestinationBlobTypeNotMatch); } } else { if (null != this.SourceBlob && this.SourceBlob.Properties.BlobType != this.destBlob.Properties.BlobType) { throw new InvalidOperationException(Resources.SourceAndDestinationBlobTypeDifferent); } } } protected override async Task<CopyState> FetchCopyStateAsync() { await this.destBlob.FetchAttributesAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); return this.destBlob.CopyState; } protected override async Task SetAttributesAsync(SetAttributesCallback setCustomAttributes) { var originalAttributes = Utils.GenerateAttributes(this.destBlob); var originalMetadata = new Dictionary<string, string>(this.destBlob.Metadata); setCustomAttributes(this.destBlob); if (!Utils.CompareProperties(originalAttributes, Utils.GenerateAttributes(this.destBlob))) { await this.destBlob.SetPropertiesAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } if (!originalMetadata.DictionaryEquals(this.destBlob.Metadata)) { await this.destBlob.SetMetadataAsync( Utils.GenerateConditionWithCustomerCondition(this.destLocation.AccessCondition), Utils.GenerateBlobRequestOptions(this.destLocation.BlobRequestOptions), Utils.GenerateOperationContext(this.TransferContext), this.CancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Diagnostics; namespace System.DirectoryServices.AccountManagement { // // A collection of individual property filters // internal class QbeFilterDescription { private readonly ArrayList _filtersToApply = new ArrayList(); public QbeFilterDescription() { // Nothing to do } public ArrayList FiltersToApply { get { return _filtersToApply; } } } // // Constructs individual property filters, given the name of the property // internal class FilterFactory { // Put a private constructor because this class should only be used as static methods private FilterFactory() { } private static readonly Hashtable s_subclasses = new Hashtable(); static FilterFactory() { s_subclasses[DescriptionFilter.PropertyNameStatic] = typeof(DescriptionFilter); s_subclasses[DisplayNameFilter.PropertyNameStatic] = typeof(DisplayNameFilter); s_subclasses[IdentityClaimFilter.PropertyNameStatic] = typeof(IdentityClaimFilter); s_subclasses[SamAccountNameFilter.PropertyNameStatic] = typeof(SamAccountNameFilter); s_subclasses[DistinguishedNameFilter.PropertyNameStatic] = typeof(DistinguishedNameFilter); s_subclasses[GuidFilter.PropertyNameStatic] = typeof(GuidFilter); s_subclasses[UserPrincipalNameFilter.PropertyNameStatic] = typeof(UserPrincipalNameFilter); s_subclasses[StructuralObjectClassFilter.PropertyNameStatic] = typeof(StructuralObjectClassFilter); s_subclasses[NameFilter.PropertyNameStatic] = typeof(NameFilter); s_subclasses[CertificateFilter.PropertyNameStatic] = typeof(CertificateFilter); s_subclasses[AuthPrincEnabledFilter.PropertyNameStatic] = typeof(AuthPrincEnabledFilter); s_subclasses[PermittedWorkstationFilter.PropertyNameStatic] = typeof(PermittedWorkstationFilter); s_subclasses[PermittedLogonTimesFilter.PropertyNameStatic] = typeof(PermittedLogonTimesFilter); s_subclasses[ExpirationDateFilter.PropertyNameStatic] = typeof(ExpirationDateFilter); s_subclasses[SmartcardLogonRequiredFilter.PropertyNameStatic] = typeof(SmartcardLogonRequiredFilter); s_subclasses[DelegationPermittedFilter.PropertyNameStatic] = typeof(DelegationPermittedFilter); s_subclasses[HomeDirectoryFilter.PropertyNameStatic] = typeof(HomeDirectoryFilter); s_subclasses[HomeDriveFilter.PropertyNameStatic] = typeof(HomeDriveFilter); s_subclasses[ScriptPathFilter.PropertyNameStatic] = typeof(ScriptPathFilter); s_subclasses[PasswordNotRequiredFilter.PropertyNameStatic] = typeof(PasswordNotRequiredFilter); s_subclasses[PasswordNeverExpiresFilter.PropertyNameStatic] = typeof(PasswordNeverExpiresFilter); s_subclasses[CannotChangePasswordFilter.PropertyNameStatic] = typeof(CannotChangePasswordFilter); s_subclasses[AllowReversiblePasswordEncryptionFilter.PropertyNameStatic] = typeof(AllowReversiblePasswordEncryptionFilter); s_subclasses[GivenNameFilter.PropertyNameStatic] = typeof(GivenNameFilter); s_subclasses[MiddleNameFilter.PropertyNameStatic] = typeof(MiddleNameFilter); s_subclasses[SurnameFilter.PropertyNameStatic] = typeof(SurnameFilter); s_subclasses[EmailAddressFilter.PropertyNameStatic] = typeof(EmailAddressFilter); s_subclasses[VoiceTelephoneNumberFilter.PropertyNameStatic] = typeof(VoiceTelephoneNumberFilter); s_subclasses[EmployeeIDFilter.PropertyNameStatic] = typeof(EmployeeIDFilter); s_subclasses[GroupIsSecurityGroupFilter.PropertyNameStatic] = typeof(GroupIsSecurityGroupFilter); s_subclasses[GroupScopeFilter.PropertyNameStatic] = typeof(GroupScopeFilter); s_subclasses[ServicePrincipalNameFilter.PropertyNameStatic] = typeof(ServicePrincipalNameFilter); s_subclasses[ExtensionCacheFilter.PropertyNameStatic] = typeof(ExtensionCacheFilter); s_subclasses[BadPasswordAttemptFilter.PropertyNameStatic] = typeof(BadPasswordAttemptFilter); s_subclasses[ExpiredAccountFilter.PropertyNameStatic] = typeof(ExpiredAccountFilter); s_subclasses[LastLogonTimeFilter.PropertyNameStatic] = typeof(LastLogonTimeFilter); s_subclasses[LockoutTimeFilter.PropertyNameStatic] = typeof(LockoutTimeFilter); s_subclasses[PasswordSetTimeFilter.PropertyNameStatic] = typeof(PasswordSetTimeFilter); s_subclasses[BadLogonCountFilter.PropertyNameStatic] = typeof(BadLogonCountFilter); } // Given a property name, constructs and returns the appropriate individual property // filter public static object CreateFilter(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "QbeFilterDescription", "FilterFactory.CreateFilter: name=" + propertyName); Type type = (Type)s_subclasses[propertyName]; Debug.Assert(type != null); return System.Activator.CreateInstance(type); } } // // The individual property filters // // Base class: Defines the external interface shared by all individual property filters internal abstract class FilterBase { public object Value { get { return _value; } set { _value = value; } } private object _value; // Some providers need place to store extra state, e.g., a processed form of Value public object Extra { get { return _extra; } set { _extra = value; } } private object _extra = null; public abstract string PropertyName { get; } } // The derived classes internal class DescriptionFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalDescription; public override string PropertyName { get { return PropertyNameStatic; } } } internal class SidFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalSid; public override string PropertyName { get { return PropertyNameStatic; } } } internal class SamAccountNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalSamAccountName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class DistinguishedNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalDistinguishedName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class GuidFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalGuid; public override string PropertyName { get { return PropertyNameStatic; } } } internal class IdentityClaimFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalIdentityClaims; public override string PropertyName { get { return PropertyNameStatic; } } } internal class UserPrincipalNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalUserPrincipalName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class StructuralObjectClassFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalStructuralObjectClass; public override string PropertyName { get { return PropertyNameStatic; } } } internal class NameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class DisplayNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalDisplayName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class CertificateFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AuthenticablePrincipalCertificates; public override string PropertyName { get { return PropertyNameStatic; } } } internal class AuthPrincEnabledFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AuthenticablePrincipalEnabled; public override string PropertyName { get { return PropertyNameStatic; } } } internal class PermittedWorkstationFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoPermittedWorkstations; public override string PropertyName { get { return PropertyNameStatic; } } } internal class PermittedLogonTimesFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoPermittedLogonTimes; public override string PropertyName { get { return PropertyNameStatic; } } } internal class ExpirationDateFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoExpirationDate; public override string PropertyName { get { return PropertyNameStatic; } } } internal class SmartcardLogonRequiredFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoSmartcardRequired; public override string PropertyName { get { return PropertyNameStatic; } } } internal class DelegationPermittedFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoDelegationPermitted; public override string PropertyName { get { return PropertyNameStatic; } } } internal class HomeDirectoryFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoHomeDirectory; public override string PropertyName { get { return PropertyNameStatic; } } } internal class HomeDriveFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoHomeDrive; public override string PropertyName { get { return PropertyNameStatic; } } } internal class ScriptPathFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoScriptPath; public override string PropertyName { get { return PropertyNameStatic; } } } internal class PasswordNotRequiredFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoPasswordNotRequired; public override string PropertyName { get { return PropertyNameStatic; } } } internal class PasswordNeverExpiresFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoPasswordNeverExpires; public override string PropertyName { get { return PropertyNameStatic; } } } internal class CannotChangePasswordFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoCannotChangePassword; public override string PropertyName { get { return PropertyNameStatic; } } } internal class AllowReversiblePasswordEncryptionFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoAllowReversiblePasswordEncryption; public override string PropertyName { get { return PropertyNameStatic; } } } internal class GivenNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserGivenName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class MiddleNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserMiddleName; public override string PropertyName { get { return PropertyNameStatic; } } } internal class SurnameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserSurname; public override string PropertyName { get { return PropertyNameStatic; } } } internal class EmailAddressFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserEmailAddress; public override string PropertyName { get { return PropertyNameStatic; } } } internal class VoiceTelephoneNumberFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserVoiceTelephoneNumber; public override string PropertyName { get { return PropertyNameStatic; } } } internal class EmployeeIDFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.UserEmployeeID; public override string PropertyName { get { return PropertyNameStatic; } } } internal class GroupIsSecurityGroupFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.GroupIsSecurityGroup; public override string PropertyName { get { return PropertyNameStatic; } } } internal class GroupScopeFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.GroupGroupScope; public override string PropertyName { get { return PropertyNameStatic; } } } internal class ServicePrincipalNameFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.ComputerServicePrincipalNames; public override string PropertyName { get { return PropertyNameStatic; } } } internal class ExtensionCacheFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PrincipalExtensionCache; public override string PropertyName { get { return PropertyNameStatic; } } } internal class BadPasswordAttemptFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoLastBadPasswordAttempt; public override string PropertyName { get { return PropertyNameStatic; } } } internal class LastLogonTimeFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoLastLogon; public override string PropertyName { get { return PropertyNameStatic; } } } internal class LockoutTimeFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoAcctLockoutTime; public override string PropertyName { get { return PropertyNameStatic; } } } internal class ExpiredAccountFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoExpiredAccount; public override string PropertyName { get { return PropertyNameStatic; } } } internal class PasswordSetTimeFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.PwdInfoLastPasswordSet; public override string PropertyName { get { return PropertyNameStatic; } } } internal class BadLogonCountFilter : FilterBase { public const string PropertyNameStatic = PropertyNames.AcctInfoBadLogonCount; public override string PropertyName { get { return PropertyNameStatic; } } } }
// 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.Build.Framework; using Microsoft.DotNet.Build.CloudTestTasks; using System; using System.IO; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Build.Construction; using System.Net.Http; using System.Xml; using System.Globalization; using System.Threading.Tasks; using System.Linq; using System.Diagnostics; using System.Threading; namespace Microsoft.DotNet.Build.Tasks { public class FinalizeBuild : AzureConnectionStringBuildTask { [Required] public string SemaphoreBlob { get; set; } [Required] public string FinalizeContainer { get; set; } public string MaxWait { get; set; } public string Delay { get; set; } [Required] public string ContainerName { get; set; } [Required] public string Channel { get; set; } [Required] public string SharedFrameworkNugetVersion { get; set; } [Required] public string SharedHostNugetVersion { get; set; } [Required] public string UWPCoreRuntimeSdkFullVersion { get; set; } [Required] public string ProductVersion { get; set; } [Required] public string Version { get; set; } [Required] public string CommitHash { get; set; } public bool ForcePublish { get; set; } private Regex _versionRegex = new Regex(@"(?<version>\d+\.\d+\.\d+)(-(?<prerelease>[^-]+-)?(?<major>\d+)-(?<minor>\d+))?"); public override bool Execute() { ParseConnectionString(); if (Log.HasLoggedErrors) { return false; } if (!FinalizeContainer.EndsWith("/")) { FinalizeContainer = $"{FinalizeContainer}/"; } string targetVersionFile = $"{FinalizeContainer}{Version}"; CreateBlobIfNotExists(SemaphoreBlob); AzureBlobLease blobLease = new AzureBlobLease(AccountName, AccountKey, ConnectionString, ContainerName, SemaphoreBlob, Log); Log.LogMessage($"Acquiring lease on semaphore blob '{SemaphoreBlob}'"); blobLease.Acquire(); // Prevent race conditions by dropping a version hint of what version this is. If we see this file // and it is the same as our version then we know that a race happened where two+ builds finished // at the same time and someone already took care of publishing and we have no work to do. if (IsLatestSpecifiedVersion(targetVersionFile) && !ForcePublish) { Log.LogMessage(MessageImportance.Low, $"version hint file for publishing finalization is {targetVersionFile}"); Log.LogMessage(MessageImportance.High, $"Version '{Version}' is already published, skipping finalization."); Log.LogMessage($"Releasing lease on semaphore blob '{SemaphoreBlob}'"); blobLease.Release(); return true; } else { // Delete old version files GetBlobList(FinalizeContainer) .Select(s => s.Replace("/dotnet/", "")) .Where(w => _versionRegex.Replace(Path.GetFileName(w), "") == "") .ToList() .ForEach(f => TryDeleteBlob(f)); // Drop the version file signaling such for any race-condition builds (see above comment). CreateBlobIfNotExists(targetVersionFile); try { CopyBlobs($"Runtime/{ProductVersion}", $"Runtime/{Channel}/"); // Generate the latest version text file string sfxVersion = GetSharedFrameworkVersionFileContent(); PublishStringToBlob(ContainerName, $"Runtime/{Channel}/latest.version", sfxVersion, "text/plain"); } finally { blobLease.Release(); } } return !Log.HasLoggedErrors; } private string GetSharedFrameworkVersionFileContent() { string returnString = $"{CommitHash}{Environment.NewLine}"; returnString += $"{SharedFrameworkNugetVersion}{Environment.NewLine}"; return returnString; } public bool CopyBlobs(string sourceFolder, string destinationFolder) { bool returnStatus = true; List<Task<bool>> copyTasks = new List<Task<bool>>(); string[] blobs = GetBlobList(sourceFolder); foreach (string blob in blobs) { string targetName = Path.GetFileName(blob) .Replace(SharedFrameworkNugetVersion, "latest") .Replace(SharedHostNugetVersion, "latest") .Replace(UWPCoreRuntimeSdkFullVersion, "latest"); string sourceBlob = blob.Replace($"/{ContainerName}/", ""); string destinationBlob = $"{destinationFolder}{targetName}"; Log.LogMessage($"Copying blob '{sourceBlob}' to '{destinationBlob}'"); copyTasks.Add(CopyBlobAsync(sourceBlob, destinationBlob)); } Task.WaitAll(copyTasks.ToArray()); copyTasks.ForEach(c => returnStatus &= c.Result); return returnStatus; } public bool TryDeleteBlob(string path) { return DeleteBlob(ContainerName, path); } public void CreateBlobIfNotExists(string path) { var blobList = GetBlobList(path); if(blobList.Count() == 0) { PublishStringToBlob(ContainerName, path, DateTime.Now.ToString()); } } public bool IsLatestSpecifiedVersion(string versionFile) { var blobList = GetBlobList(versionFile); return blobList.Count() != 0; } public bool DeleteBlob(string container, string blob) { return DeleteAzureBlob.Execute(AccountName, AccountKey, ConnectionString, container, blob, BuildEngine, HostObject); } public Task<bool> CopyBlobAsync(string sourceBlobName, string destinationBlobName) { return CopyAzureBlobToBlob.ExecuteAsync(AccountName, AccountKey, ConnectionString, ContainerName, sourceBlobName, destinationBlobName, BuildEngine, HostObject); } public string[] GetBlobList(string path) { return ListAzureBlobs.Execute(AccountName, AccountKey, ConnectionString, ContainerName, path, BuildEngine, HostObject); } public bool PublishStringToBlob(string container, string blob, string contents, string contentType = null) { return PublishStringToAzureBlob.Execute(AccountName, AccountKey, ConnectionString, container, blob, contents, contentType, BuildEngine, HostObject); } } }
/* * 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 FlagsAttribute = Lucene.Net.Analysis.Tokenattributes.FlagsAttribute; using OffsetAttribute = Lucene.Net.Analysis.Tokenattributes.OffsetAttribute; using PayloadAttribute = Lucene.Net.Analysis.Tokenattributes.PayloadAttribute; using PositionIncrementAttribute = Lucene.Net.Analysis.Tokenattributes.PositionIncrementAttribute; using TermAttribute = Lucene.Net.Analysis.Tokenattributes.TermAttribute; using TypeAttribute = Lucene.Net.Analysis.Tokenattributes.TypeAttribute; using Payload = Lucene.Net.Index.Payload; using AttributeImpl = Lucene.Net.Util.AttributeImpl; namespace Lucene.Net.Analysis { /// <summary> This class wraps a Token and supplies a single attribute instance /// where the delegate token can be replaced. /// </summary> /// <deprecated> Will be removed, when old TokenStream API is removed. /// </deprecated> [Obsolete("Will be removed, when old TokenStream API is removed.")] [Serializable] public sealed class TokenWrapper:AttributeImpl, System.ICloneable, TermAttribute, TypeAttribute, PositionIncrementAttribute, FlagsAttribute, OffsetAttribute, PayloadAttribute { internal Token delegate_Renamed; internal TokenWrapper():this(new Token()) { } internal TokenWrapper(Token delegate_Renamed) { this.delegate_Renamed = delegate_Renamed; } // TermAttribute: public System.String Term() { return delegate_Renamed.Term(); } public void SetTermBuffer(char[] buffer, int offset, int length) { delegate_Renamed.SetTermBuffer(buffer, offset, length); } public void SetTermBuffer(System.String buffer) { delegate_Renamed.SetTermBuffer(buffer); } public void SetTermBuffer(System.String buffer, int offset, int length) { delegate_Renamed.SetTermBuffer(buffer, offset, length); } public char[] TermBuffer() { return delegate_Renamed.TermBuffer(); } public char[] ResizeTermBuffer(int newSize) { return delegate_Renamed.ResizeTermBuffer(newSize); } public int TermLength() { return delegate_Renamed.TermLength(); } public void SetTermLength(int length) { delegate_Renamed.SetTermLength(length); } // TypeAttribute: public System.String Type() { return delegate_Renamed.Type(); } public void SetType(System.String type) { delegate_Renamed.SetType(type); } public void SetPositionIncrement(int positionIncrement) { delegate_Renamed.SetPositionIncrement(positionIncrement); } public int GetPositionIncrement() { return delegate_Renamed.GetPositionIncrement(); } // FlagsAttribute public int GetFlags() { return delegate_Renamed.GetFlags(); } public void SetFlags(int flags) { delegate_Renamed.SetFlags(flags); } // OffsetAttribute public int StartOffset() { return delegate_Renamed.StartOffset(); } public void SetOffset(int startOffset, int endOffset) { delegate_Renamed.SetOffset(startOffset, endOffset); } public int EndOffset() { return delegate_Renamed.EndOffset(); } // PayloadAttribute public Payload GetPayload() { return delegate_Renamed.GetPayload(); } public void SetPayload(Payload payload) { delegate_Renamed.SetPayload(payload); } // AttributeImpl public override void Clear() { delegate_Renamed.Clear(); } public override System.String ToString() { return delegate_Renamed.ToString(); } public override int GetHashCode() { return delegate_Renamed.GetHashCode(); } public override bool Equals(System.Object other) { if (other is TokenWrapper) { return ((TokenWrapper) other).delegate_Renamed.Equals(this.delegate_Renamed); } return false; } public override System.Object Clone() { return new TokenWrapper((Token) delegate_Renamed.Clone()); } public override void CopyTo(AttributeImpl target) { if (target is TokenWrapper) { ((TokenWrapper) target).delegate_Renamed = (Token) this.delegate_Renamed.Clone(); } else { this.delegate_Renamed.CopyTo(target); } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using WeifenLuo.WinFormsUI.ThemeVS2005; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] internal class VS2005DockPaneStrip : DockPaneStripBase { private class TabVS2005 : Tab { public TabVS2005(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override DockPaneStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } [ToolboxItem(false)] private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } public override Bitmap HoverImage { get { return null; } } public override Bitmap PressImage { get { return null; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 1; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 4; private const int _DocumentButtonGapBottom = 4; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 3; private const int _DocumentTabGapLeft = 3; private const int _DocumentTabGapRight = 3; private const int _DocumentIconGapBottom = 2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 3; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.GrayText; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2005DockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); pane.DockPanel.Theme.ApplyTo(m_selectMenu); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop + (PatchController.EnableHighDpi == true ? DocumentIconGapBottom : 0), ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } public override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = Tabs[index].Rectangle.Value; rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = Tabs[index].Rectangle.Value; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2005 tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2005 tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; TabVS2005 tab = Tabs[index] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X + rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X + rectTabStrip.Height / 2; foreach (TabVS2005 tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); if (index == -1) { //somehow we've lost the content from the Tab collection return false; } TabVS2005 tab = Tabs[index] as TabVS2005; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); if (DockPane.DockPanel.ShowDocumentIcon) return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2005 tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2005; tabActive.Rectangle = rectTab; continue; } if (rectTab.IntersectsWith(rectTabOnly)) { var tab = Tabs[i] as TabVS2005; tab.Rectangle = rectTab; DrawTab(g, tab); } } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1, rectTabStrip.Right, rectTabStrip.Bottom - 1); g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = tabActive.Rectangle.Value; if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); tabActive.Rectangle = rectTab; DrawTab(g, tabActive); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) { var tab = Tabs[i] as TabVS2005; tab.Rectangle = GetTabRectangle(i); DrawTab(g, tab); } } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2005 tab = (TabVS2005)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2005 tab) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab); else DrawTab_Document(g, tab); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { int curveSize = 6; GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); // Draws the full angle piece for active content (or first tab) if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. // It is not needed so it has been commented out. //GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom); GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } // Draws the partial angle for non-active content else { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); } else { GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); } } } if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } else { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, rect.Left + curveSize / 2, rect.Top); GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { // Draws the bottom horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, rect.Right - curveSize / 2, rect.Bottom); // Drawing the rounded corner is not necessary. The path is automatically connected //GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90); } else { // Draws the top horizontal line (short side) GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top); // Draws the rounded corner oppposite the angled side GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); } } if (Tabs.IndexOf(tab) != EndDisplayingTab && (Tabs.IndexOf(tab) != Tabs.Count - 1 && Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent) && !full) { if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, rect.Bottom); } } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Bottom - rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, rect.Top); } else { GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Top + rect.Height / 2); GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, rect.Bottom); } } } else { // Draw the vertical line opposite the angled side if (RightToLeft == RightToLeft.Yes) { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); else GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom); } else { if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top); else GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); } } return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab) { var rect = tab.Rectangle.Value; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = PatchController.EnableHighDpi == true ? new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - TextFont.Height, ToolWindowImageWidth, TextFont.Height) : rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rectTab, startColor, endColor, gradientMode)) { g.FillPath(brush, path); } g.DrawPath(PenToolWindowTabBorder, path); Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.LinearGradientMode; using (LinearGradientBrush brush1 = new LinearGradientBrush(rectTab, startColor, endColor, gradientMode)) { g.FillPath(brush1, path); } if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) { Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop); Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom); g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), DrawHelper.RtlTransform(this, pt2)); } Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2005 tab) { var rect = tab.Rectangle.Value; if (tab.TabWidth == 0) return; Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = PatchController.EnableHighDpi == true ? new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - TextFont.Height, DocumentIconWidth, TextFont.Height) : rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += DocumentIconGapLeft; rectBack.X -= DocumentIconGapLeft; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); GraphicsPath path = GetTabOutline(tab, true, false); if (DockPane.ActiveContent == tab.Content) { Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rectBack, startColor, endColor, gradientMode)) { g.FillPath(brush, path); } g.DrawPath(PenDocumentTabActiveBorder, path); Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; if (DockPane.IsActiveDocumentPane) TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, DocumentTextFormat); else TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } else { Color startColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.LinearGradientMode; using (LinearGradientBrush brush1 = new LinearGradientBrush(rectBack, startColor, endColor, gradientMode)) { g.FillPath(brush1, path); } g.DrawPath(PenDocumentTabInactiveBorder, path); Color textColor = DockPane.DockPanel.Theme.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, DocumentTextFormat); } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2005 tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButton; m_closeButtonVisible = DockPane.ActiveContent == null ? true : DockPane.ActiveContent.DockHandler.CloseButtonVisible; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * height / buttonHeight; buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); if (PatchController.EnableMemoryLeakFix == true) { ContentClosed(); } } protected override int HitTest(Point point) { if (!TabsRectangle.Contains(point)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(point)) return Tabs.IndexOf(tab); } return -1; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline(tab, true, false); RectangleF rectangle = path.GetBounds(); return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(Control.MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); if (index != -1) { TabVS2005 tab = Tabs[index] as TabVS2005; if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; } if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }