context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
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.Swizzle
{
/// <summary>
/// Temporary vector of type T with 2 components, used for implementing swizzling for gvec2.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct swizzle_gvec2<T>
{
#region Fields
/// <summary>
/// x-component
/// </summary>
internal readonly T x;
/// <summary>
/// y-component
/// </summary>
internal readonly T y;
#endregion
#region Constructors
/// <summary>
/// Constructor for swizzle_gvec2.
/// </summary>
internal swizzle_gvec2(T x, T y)
{
this.x = x;
this.y = y;
}
#endregion
#region Properties
/// <summary>
/// Returns gvec2.xx swizzling.
/// </summary>
public gvec2<T> xx => new gvec2<T>(x, x);
/// <summary>
/// Returns gvec2.rr swizzling (equivalent to gvec2.xx).
/// </summary>
public gvec2<T> rr => new gvec2<T>(x, x);
/// <summary>
/// Returns gvec2.xxx swizzling.
/// </summary>
public gvec3<T> xxx => new gvec3<T>(x, x, x);
/// <summary>
/// Returns gvec2.rrr swizzling (equivalent to gvec2.xxx).
/// </summary>
public gvec3<T> rrr => new gvec3<T>(x, x, x);
/// <summary>
/// Returns gvec2.xxxx swizzling.
/// </summary>
public gvec4<T> xxxx => new gvec4<T>(x, x, x, x);
/// <summary>
/// Returns gvec2.rrrr swizzling (equivalent to gvec2.xxxx).
/// </summary>
public gvec4<T> rrrr => new gvec4<T>(x, x, x, x);
/// <summary>
/// Returns gvec2.xxxy swizzling.
/// </summary>
public gvec4<T> xxxy => new gvec4<T>(x, x, x, y);
/// <summary>
/// Returns gvec2.rrrg swizzling (equivalent to gvec2.xxxy).
/// </summary>
public gvec4<T> rrrg => new gvec4<T>(x, x, x, y);
/// <summary>
/// Returns gvec2.xxy swizzling.
/// </summary>
public gvec3<T> xxy => new gvec3<T>(x, x, y);
/// <summary>
/// Returns gvec2.rrg swizzling (equivalent to gvec2.xxy).
/// </summary>
public gvec3<T> rrg => new gvec3<T>(x, x, y);
/// <summary>
/// Returns gvec2.xxyx swizzling.
/// </summary>
public gvec4<T> xxyx => new gvec4<T>(x, x, y, x);
/// <summary>
/// Returns gvec2.rrgr swizzling (equivalent to gvec2.xxyx).
/// </summary>
public gvec4<T> rrgr => new gvec4<T>(x, x, y, x);
/// <summary>
/// Returns gvec2.xxyy swizzling.
/// </summary>
public gvec4<T> xxyy => new gvec4<T>(x, x, y, y);
/// <summary>
/// Returns gvec2.rrgg swizzling (equivalent to gvec2.xxyy).
/// </summary>
public gvec4<T> rrgg => new gvec4<T>(x, x, y, y);
/// <summary>
/// Returns gvec2.xy swizzling.
/// </summary>
public gvec2<T> xy => new gvec2<T>(x, y);
/// <summary>
/// Returns gvec2.rg swizzling (equivalent to gvec2.xy).
/// </summary>
public gvec2<T> rg => new gvec2<T>(x, y);
/// <summary>
/// Returns gvec2.xyx swizzling.
/// </summary>
public gvec3<T> xyx => new gvec3<T>(x, y, x);
/// <summary>
/// Returns gvec2.rgr swizzling (equivalent to gvec2.xyx).
/// </summary>
public gvec3<T> rgr => new gvec3<T>(x, y, x);
/// <summary>
/// Returns gvec2.xyxx swizzling.
/// </summary>
public gvec4<T> xyxx => new gvec4<T>(x, y, x, x);
/// <summary>
/// Returns gvec2.rgrr swizzling (equivalent to gvec2.xyxx).
/// </summary>
public gvec4<T> rgrr => new gvec4<T>(x, y, x, x);
/// <summary>
/// Returns gvec2.xyxy swizzling.
/// </summary>
public gvec4<T> xyxy => new gvec4<T>(x, y, x, y);
/// <summary>
/// Returns gvec2.rgrg swizzling (equivalent to gvec2.xyxy).
/// </summary>
public gvec4<T> rgrg => new gvec4<T>(x, y, x, y);
/// <summary>
/// Returns gvec2.xyy swizzling.
/// </summary>
public gvec3<T> xyy => new gvec3<T>(x, y, y);
/// <summary>
/// Returns gvec2.rgg swizzling (equivalent to gvec2.xyy).
/// </summary>
public gvec3<T> rgg => new gvec3<T>(x, y, y);
/// <summary>
/// Returns gvec2.xyyx swizzling.
/// </summary>
public gvec4<T> xyyx => new gvec4<T>(x, y, y, x);
/// <summary>
/// Returns gvec2.rggr swizzling (equivalent to gvec2.xyyx).
/// </summary>
public gvec4<T> rggr => new gvec4<T>(x, y, y, x);
/// <summary>
/// Returns gvec2.xyyy swizzling.
/// </summary>
public gvec4<T> xyyy => new gvec4<T>(x, y, y, y);
/// <summary>
/// Returns gvec2.rggg swizzling (equivalent to gvec2.xyyy).
/// </summary>
public gvec4<T> rggg => new gvec4<T>(x, y, y, y);
/// <summary>
/// Returns gvec2.yx swizzling.
/// </summary>
public gvec2<T> yx => new gvec2<T>(y, x);
/// <summary>
/// Returns gvec2.gr swizzling (equivalent to gvec2.yx).
/// </summary>
public gvec2<T> gr => new gvec2<T>(y, x);
/// <summary>
/// Returns gvec2.yxx swizzling.
/// </summary>
public gvec3<T> yxx => new gvec3<T>(y, x, x);
/// <summary>
/// Returns gvec2.grr swizzling (equivalent to gvec2.yxx).
/// </summary>
public gvec3<T> grr => new gvec3<T>(y, x, x);
/// <summary>
/// Returns gvec2.yxxx swizzling.
/// </summary>
public gvec4<T> yxxx => new gvec4<T>(y, x, x, x);
/// <summary>
/// Returns gvec2.grrr swizzling (equivalent to gvec2.yxxx).
/// </summary>
public gvec4<T> grrr => new gvec4<T>(y, x, x, x);
/// <summary>
/// Returns gvec2.yxxy swizzling.
/// </summary>
public gvec4<T> yxxy => new gvec4<T>(y, x, x, y);
/// <summary>
/// Returns gvec2.grrg swizzling (equivalent to gvec2.yxxy).
/// </summary>
public gvec4<T> grrg => new gvec4<T>(y, x, x, y);
/// <summary>
/// Returns gvec2.yxy swizzling.
/// </summary>
public gvec3<T> yxy => new gvec3<T>(y, x, y);
/// <summary>
/// Returns gvec2.grg swizzling (equivalent to gvec2.yxy).
/// </summary>
public gvec3<T> grg => new gvec3<T>(y, x, y);
/// <summary>
/// Returns gvec2.yxyx swizzling.
/// </summary>
public gvec4<T> yxyx => new gvec4<T>(y, x, y, x);
/// <summary>
/// Returns gvec2.grgr swizzling (equivalent to gvec2.yxyx).
/// </summary>
public gvec4<T> grgr => new gvec4<T>(y, x, y, x);
/// <summary>
/// Returns gvec2.yxyy swizzling.
/// </summary>
public gvec4<T> yxyy => new gvec4<T>(y, x, y, y);
/// <summary>
/// Returns gvec2.grgg swizzling (equivalent to gvec2.yxyy).
/// </summary>
public gvec4<T> grgg => new gvec4<T>(y, x, y, y);
/// <summary>
/// Returns gvec2.yy swizzling.
/// </summary>
public gvec2<T> yy => new gvec2<T>(y, y);
/// <summary>
/// Returns gvec2.gg swizzling (equivalent to gvec2.yy).
/// </summary>
public gvec2<T> gg => new gvec2<T>(y, y);
/// <summary>
/// Returns gvec2.yyx swizzling.
/// </summary>
public gvec3<T> yyx => new gvec3<T>(y, y, x);
/// <summary>
/// Returns gvec2.ggr swizzling (equivalent to gvec2.yyx).
/// </summary>
public gvec3<T> ggr => new gvec3<T>(y, y, x);
/// <summary>
/// Returns gvec2.yyxx swizzling.
/// </summary>
public gvec4<T> yyxx => new gvec4<T>(y, y, x, x);
/// <summary>
/// Returns gvec2.ggrr swizzling (equivalent to gvec2.yyxx).
/// </summary>
public gvec4<T> ggrr => new gvec4<T>(y, y, x, x);
/// <summary>
/// Returns gvec2.yyxy swizzling.
/// </summary>
public gvec4<T> yyxy => new gvec4<T>(y, y, x, y);
/// <summary>
/// Returns gvec2.ggrg swizzling (equivalent to gvec2.yyxy).
/// </summary>
public gvec4<T> ggrg => new gvec4<T>(y, y, x, y);
/// <summary>
/// Returns gvec2.yyy swizzling.
/// </summary>
public gvec3<T> yyy => new gvec3<T>(y, y, y);
/// <summary>
/// Returns gvec2.ggg swizzling (equivalent to gvec2.yyy).
/// </summary>
public gvec3<T> ggg => new gvec3<T>(y, y, y);
/// <summary>
/// Returns gvec2.yyyx swizzling.
/// </summary>
public gvec4<T> yyyx => new gvec4<T>(y, y, y, x);
/// <summary>
/// Returns gvec2.gggr swizzling (equivalent to gvec2.yyyx).
/// </summary>
public gvec4<T> gggr => new gvec4<T>(y, y, y, x);
/// <summary>
/// Returns gvec2.yyyy swizzling.
/// </summary>
public gvec4<T> yyyy => new gvec4<T>(y, y, y, y);
/// <summary>
/// Returns gvec2.gggg swizzling (equivalent to gvec2.yyyy).
/// </summary>
public gvec4<T> gggg => new gvec4<T>(y, y, y, y);
#endregion
}
}
| |
namespace Nancy.ViewEngines.DotLiquid.Tests
{
using System.Collections.Generic;
using System.IO;
using Configuration;
using FakeItEasy;
using global::DotLiquid;
using global::DotLiquid.Exceptions;
using Nancy.Tests;
using Xunit;
using Xunit.Extensions;
public class LiquidNancyFileSystemFixture
{
private readonly INancyEnvironment environment;
public LiquidNancyFileSystemFixture()
{
this.environment = new DefaultNancyEnvironment();
this.environment.AddValue(ViewConfiguration.Default);
}
[Fact]
public void Should_locate_template_with_single_quoted_name()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "'views/partial'");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_locate_template_with_double_quoted_name()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"""views/partial""");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_locate_template_with_unquoted_name()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_not_locate_templates_that_does_not_have_liquid_extension()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "cshtml", () => null));
// When
var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "views/partial"));
// Then
exception.ShouldBeOfType<FileSystemException>();
}
[Theory]
[InlineData("partial")]
[InlineData("paRTial")]
[InlineData("PARTIAL")]
public void Should_ignore_casing_of_template_name(string templateName)
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat("views/", templateName));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_locating_template_when_template_name_contains_liquid_extension()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial.liquid");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_locating_template_when_template_name_does_not_contains_liquid_extension()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, "views/partial");
// Then
result.ShouldEqual("The correct view");
}
[Theory]
[InlineData("liquid")]
[InlineData("liqUID")]
[InlineData("LIQUID")]
public void Should_ignore_extension_casing_when_template_name_contains_liquid_extension(string extension)
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat("views/partial.", extension));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_not_locate_view_when_template_location_not_specified()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult("views", "partial", "liquid", () => null));
// When
var exception = Record.Exception(() => fileSystem.ReadTemplateFile(context, "partial"));
// Then
exception.ShouldBeOfType<FileSystemException>();
}
[Theory]
[InlineData("views", "Located in views/")]
[InlineData("views/shared", "Located in views/shared")]
public void Should_locate_templates_with_correct_location_specified(string location, string expectedResult)
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult(location, "partial", "liquid", () => new StringReader(expectedResult)));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial"));
// Then
result.ShouldEqual(expectedResult);
}
[Theory]
[InlineData("views")]
[InlineData("viEws")]
[InlineData("VIEWS")]
public void Should_ignore_case_of_location_when_locating_template(string location)
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult(location, "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, string.Concat(location, "/partial"));
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_backslashes_as_location_seperator()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"views\shared\partial");
// Then
result.ShouldEqual("The correct view");
}
[Fact]
public void Should_support_forward_slashes_as_location_seperator()
{
// Given
Context context;
var fileSystem = this.CreateFileSystem(out context,
new ViewLocationResult(@"views/shared", "partial", "liquid", () => new StringReader("The correct view")));
// When
var result = fileSystem.ReadTemplateFile(context, @"views/shared/partial");
// Then
result.ShouldEqual("The correct view");
}
private LiquidNancyFileSystem CreateFileSystem(out Context context, params ViewLocationResult[] viewLocationResults)
{
var viewLocationProvider = A.Fake<IViewLocationProvider>();
A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._))
.Returns(viewLocationResults);
var viewEngine = A.Fake<IViewEngine>();
A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" });
var viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment);
var startupContext = new ViewEngineStartupContext(
null,
viewLocator);
var renderContext = A.Fake<IRenderContext>();
A.CallTo(() => renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))
.ReturnsLazily(x => viewLocator.LocateView(x.Arguments.Get<string>(0), null));
context = new Context(new List<Hash>(), new Hash(),
Hash.FromAnonymousObject(new { nancy = renderContext }), false);
return new LiquidNancyFileSystem(startupContext, new[] { "liquid" });
}
}
}
| |
using System;
using System.Text;
namespace StriderMqtt
{
internal class ConnectPacket : PacketBase
{
internal const byte PacketTypeCode = 0x01;
internal const string ProtocolNameV3_1 = "MQIsdp";
internal const string ProtocolNameV3_1_1 = "MQTT";
// max length for client id (removed in 3.1.1)
internal const int ClientIdMaxLength = 23;
internal const ushort KeepAlivePeriodDefault = 60; // seconds
// connect flags
internal const byte UsernameFlagOffset = 0x07;
internal const byte PasswordFlagOffset = 0x06;
internal const byte WillRetainFlagOffset = 0x05;
internal const byte WillQosFlagOffset = 0x03;
internal const byte WillFlagOffset = 0x02;
internal const byte CleanSessionFlagOffset = 0x01;
internal MqttProtocolVersion ProtocolVersion { get; set; }
internal string ClientId { get; set; }
internal bool WillRetain { get; set; }
internal MqttQos WillQosLevel { get; set; }
internal bool WillFlag { get; set; }
internal string WillTopic { get; set; }
internal byte[] WillMessage { get; set; }
internal string Username { get; set; }
internal string Password { get; set; }
internal bool CleanSession { get; set; }
internal ushort KeepAlivePeriod { get; set; }
internal ConnectPacket()
{
this.PacketType = PacketTypeCode;
}
/// <summary>
/// Reads a Connect packet from the given stream.
/// (This method should not be used since clients don't receive Connect packets)
/// </summary>
/// <param name="fixedHeaderFirstByte">Fixed header first byte previously read</param>
/// <param name="stream">The stream to read from</param>
/// <param name="protocolVersion">The protocol version to be used to read</param>
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Connect packet should not be received");
}
/// <summary>
/// Writes the Connect packet to the given stream and using the given
/// protocol version.
/// </summary>
/// <param name="stream">The stream to write to</param>
/// <param name="protocolVersion">Protocol to be used to write</param>
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
// will flag set, will topic and will message MUST be present
if (this.WillFlag && (WillMessage == null || String.IsNullOrEmpty(WillTopic)))
{
throw new MqttProtocolException("Last will message is invalid");
}
// willflag not set, retain must be 0 and will topic and message MUST NOT be present
else if (!this.WillFlag && (this.WillRetain || WillMessage != null || !String.IsNullOrEmpty(WillTopic)))
{
throw new MqttProtocolException("Last will message is invalid");
}
}
if (this.WillFlag && ((this.WillTopic.Length < Packet.MinTopicLength) || (this.WillTopic.Length > Packet.MaxTopicLength)))
{
throw new MqttProtocolException("Invalid last will topic length");
}
writer.SetFixedHeader(PacketType);
MakeVariableHeader(writer);
MakePayload(writer);
}
void MakeVariableHeader(PacketWriter w)
{
if (this.ProtocolVersion == MqttProtocolVersion.V3_1)
{
w.AppendTextField(ProtocolNameV3_1);
}
else
{
w.AppendTextField(ProtocolNameV3_1_1);
}
w.Append((byte)this.ProtocolVersion);
w.Append(MakeConnectFlags());
w.AppendIntegerField(KeepAlivePeriod);
}
byte MakeConnectFlags()
{
byte connectFlags = 0x00;
connectFlags |= (Username != null) ? (byte)(1 << UsernameFlagOffset) : (byte)0x00;
connectFlags |= (Password != null) ? (byte)(1 << PasswordFlagOffset) : (byte)0x00;
connectFlags |= (this.WillRetain) ? (byte)(1 << WillRetainFlagOffset) : (byte)0x00;
if (this.WillFlag)
connectFlags |= (byte)((byte)WillQosLevel << WillQosFlagOffset);
connectFlags |= (this.WillFlag) ? (byte)(1 << WillFlagOffset) : (byte)0x00;
connectFlags |= (this.CleanSession) ? (byte)(1 << CleanSessionFlagOffset) : (byte)0x00;
return connectFlags;
}
void MakePayload(PacketWriter w)
{
w.AppendTextField(ClientId);
if (!String.IsNullOrEmpty(WillTopic))
{
w.AppendTextField(WillTopic);
}
if (WillMessage != null)
{
w.AppendBytesField(WillMessage);
}
if (Username != null)
{
w.AppendTextField(Username);
}
if (Password != null)
{
w.AppendTextField(Password);
}
}
}
internal class ConnackPacket : PacketBase
{
internal const byte PacketTypeCode = 0x02;
private const byte SessionPresentFlag = 0x01;
internal bool SessionPresent {
get;
private set;
}
internal ConnackReturnCode ReturnCode {
get;
private set;
}
internal ConnackPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Clients should not send connack packets");
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
if ((reader.FixedHeaderFirstByte & Packet.PacketFlagsBitMask) != Packet.ZeroedHeaderFlagBits)
{
throw new MqttProtocolException("Connack packet received with invalid header flags");
}
}
if (reader.RemainingLength != 2)
{
throw new MqttProtocolException("Connack packet received with invalid remaining length");
}
this.SessionPresent = (reader.ReadByte() & SessionPresentFlag) > 0;
this.ReturnCode = (ConnackReturnCode)reader.ReadByte();
}
}
internal class PingreqPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0C;
internal const byte PingreqFlagBits = 0x00;
internal PingreqPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
writer.SetFixedHeader(this.PacketType);
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Pingreq packet should not be received");
}
}
internal class PingrespPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0D;
internal PingrespPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Clients should not send pingresp packets");
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
if (protocolVersion == MqttProtocolVersion.V3_1_1)
{
if ((reader.FixedHeaderFirstByte & Packet.PacketFlagsBitMask) != Packet.ZeroedHeaderFlagBits)
{
throw new MqttProtocolException("Pingresp packet received with invalid header flags");
}
}
if (reader.RemainingLength != 0)
{
throw new MqttProtocolException("Pingresp packet received with invalid remaining length");
}
}
}
internal class DisconnectPacket : PacketBase
{
internal const byte PacketTypeCode = 0x0E;
internal DisconnectPacket()
{
this.PacketType = PacketTypeCode;
}
internal override void Deserialize(PacketReader reader, MqttProtocolVersion protocolVersion)
{
throw new MqttProtocolException("Disconnect packet should not be received");
}
internal override void Serialize(PacketWriter writer, MqttProtocolVersion protocolVersion)
{
writer.SetFixedHeader(PacketType);
}
}
}
| |
/*
* Copyright 2005 OpenXRI Foundation
* Subsequently ported and altered by Andrew Arnott and Troels Thomsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
namespace DotNetXri.Syntax
{
/// <summary>
/// This class provides a strong typing for a XRI. Any
/// obj of this class that appears outside of the package is a valid
/// XRI. THERE ARE INTENTIONALLY NO SET METHODS. Use this class like
/// java.lang.String or java.net.URI
/// </summary>
public class XRI : Parsable, XRIReference
{
public const string PDELIM_S = "!";
public const string RDELIM_S = "*";
public const char PDELIM = '!';
public const char RDELIM = '*';
public const string XRI_SCHEME = "xri://";
public static readonly int XRI_SCHEME_LENGTH = XRI_SCHEME.Length;
AuthorityPath moAuthorityPath = null;
XRIAbsolutePath moAbsolutePath = null;
XRIQuery query = null;
XRIFragment fragment = null;
/// <summary>
/// Protected Constructor used by package only
/// </summary>
internal XRI()
{ }
/// <summary>
/// Constructs an XRI from the provided XRI
/// </summary>
/// <param name="oXRI"></param>
public XRI(XRI oXRI)
{
moAuthorityPath = oXRI.AuthorityPath;
moAbsolutePath = oXRI.XRIAbsolutePath;
query = oXRI.Query;
fragment = oXRI.Fragment;
setParsedXRI();
}
/// <summary>
/// absolute path
/// </summary>
public XRIAbsolutePath XRIAbsolutePath
{
get
{
return moAbsolutePath;
}
}
/// <summary>
/// Constructs XRI from String
/// </summary>
/// <param name="sXRI"></param>
public XRI(string sXRI)
: base(sXRI)
{
parse();
}
/// <summary>
/// Constructs an XRI from the provided AuthorityPath
/// </summary>
/// <param name="oAuthority"></param>
public XRI(AuthorityPath oAuthority)
{
moAuthorityPath = oAuthority;
setParsedXRI();
}
/// <summary>
/// Constructs an XRI from the provided AuthorityPath and LocalPath
/// </summary>
/// <param name="oAuthority"></param>
/// <param name="oPath"></param>
public XRI(AuthorityPath oAuthority, XRIPath oPath)
{
if (oAuthority == null)
{
throw new XRIParseException();
}
moAuthorityPath = oAuthority;
if (oPath != null)
{
if (oPath is XRINoSchemePath)
{
moAbsolutePath = new XRIAbsolutePath((XRINoSchemePath)oPath);
}
else if (oPath is XRIAbsolutePath)
{
moAbsolutePath = (XRIAbsolutePath)oPath;
}
}
setParsedXRI();
}
/// <summary>
/// Constructs an XRI from the provided AuthorityPath, LocalPath, Query and Fragment
/// </summary>
/// <param name="oAuthority"></param>
/// <param name="oPath"></param>
/// <param name="query"></param>
/// <param name="fragment"></param>
public XRI(AuthorityPath oAuthority, XRIPath oPath, XRIQuery query, XRIFragment fragment)
{
if (oAuthority == null)
{
throw new XRIParseException();
}
moAuthorityPath = oAuthority;
if (oPath != null)
{
if (oPath is XRINoSchemePath)
{
moAbsolutePath = new XRIAbsolutePath((XRINoSchemePath)oPath);
}
else if (oPath is XRIAbsolutePath)
{
moAbsolutePath = (XRIAbsolutePath)oPath;
}
}
this.query = query;
this.fragment = fragment;
setParsedXRI();
}
/// <summary>
/// Constructs an XRI from the provided XRI reference in IRI Normal Form
/// </summary>
/// <param name="iri"></param>
/// <returns></returns>
public static XRI fromIRINormalForm(string iri)
{
string xriNF = IRIUtils.IRItoXRI(iri);
return new XRI(xriNF);
}
/// <summary>
/// Constructs an XRI from the provided XRI reference in URI Normal Form
/// </summary>
/// <param name="uri"></param>
/// <returns></returns>
public static XRI fromURINormalForm(string uri)
{
string iriNF;
try
{
iriNF = IRIUtils.URItoIRI(uri);
}
catch (UnsupportedEncodingException e)
{
// we're only using UTF-8 which should really be there in every JVM
throw new XRIParseException("UTF-8 encoding not supported: " + e.getMessage());
}
string xriNF = IRIUtils.IRItoXRI(iriNF);
return new XRI(xriNF);
}
/// <summary>
/// This is used by constructors that need to set the parsed value
/// without actually parsing the XRI.
/// </summary>
void setParsedXRI()
{
string sValue = XRI_SCHEME + moAuthorityPath.ToString();
// add the local path and relative path as necessary
if (moAbsolutePath != null)
{
sValue += moAbsolutePath.ToString();
}
if (query != null)
{
sValue += query.ToString();
}
if (fragment != null)
{
sValue += query.ToString();
}
setParsedValue(sValue);
}
/// <summary>
/// returns true if the XRI is absolute
/// </summary>
/// <returns></returns>
public bool isAbsolute()
{
parse();
return (moAuthorityPath != null);
}
/// <summary>
/// returns returns true if the XRI is relative
/// </summary>
/// <returns></returns>
public bool isRelative()
{
return !isAbsolute();
}
/// <summary>
/// Parses the input stream into an Authority Path
/// </summary>
/// <param name="oParseStream">The input stream to scan from</param>
/// <returns></returns>
static AuthorityPath scanSchemeAuthority(ParseStream oParseStream)
{
if (oParseStream.empty())
{
return null;
}
ParseStream oAuthStream = oParseStream.begin();
// The xri:// is optional
if ((oParseStream.getData().Length >= XRI_SCHEME_LENGTH))
{
string sScheme = oAuthStream.getData().Substring(0, XRI_SCHEME_LENGTH);
if ((sScheme != null) && sScheme.Equals(XRI_SCHEME, StringComparison.InvariantCultureIgnoreCase))
{
oAuthStream.consume(XRI_SCHEME_LENGTH);
}
}
// see if we get an authority
AuthorityPath oAuthorityPath = AuthorityPath.scanAuthority(oAuthStream);
// if we found one, consume the entire auth stream, including
// the scheme
if (oAuthorityPath != null)
{
oParseStream.end(oAuthStream);
}
return oAuthorityPath;
}
public string ToString(bool wantScheme, bool caseFoldAuthority)
{
StringBuilder sb = new StringBuilder();
if (moAuthorityPath != null)
{
if (wantScheme)
{
sb.Append(XRI_SCHEME);
}
string a = moAuthorityPath.ToString();
if (caseFoldAuthority)
a = a.ToLower();
sb.Append(a);
}
if (moAbsolutePath != null)
sb.Append(moAbsolutePath.ToString());
if (query != null)
{
sb.Append("?");
sb.Append(query.ToString());
}
if (fragment != null)
{
sb.Append("#");
sb.Append(fragment.ToString());
}
return sb.ToString();
}
public bool Equals(XRI x)
{
return ToString(false, true).Equals(x.ToString(false, true));
}
public string toIRINormalForm()
{
string iri = "";
// add the authority path if it is there
if (moAuthorityPath != null)
{
iri = XRI_SCHEME + moAuthorityPath.toIRINormalForm();
}
// add the local path and relative path as necessary
if (moAbsolutePath != null)
{
iri += moAbsolutePath.toIRINormalForm();
}
if (query != null)
iri += "?" + query.toIRINormalForm();
if (fragment != null)
iri += "#" + fragment.toIRINormalForm();
return iri;
}
/// <summary>
/// Serializes the XRI into IRI normal from
/// </summary>
/// <returns>The IRI normal form of the XRI</returns>
public string toURINormalForm()
{
string iri = toIRINormalForm();
return IRIUtils.IRItoURI(iri);
}
/// <summary>
/// Parses the input stream into the obj
/// </summary>
/// <param name="oStream">The input stream to scan from</param>
/// <returns>True if part of the Stream was consumed into the obj</returns>
bool doScan(ParseStream oStream)
{
moAuthorityPath = scanSchemeAuthority(oStream);
if (moAuthorityPath == null)
{
return false;
}
XRIAbsolutePath oPath = new XRIAbsolutePath();
if (oPath.scan(oStream))
{
moAbsolutePath = oPath;
}
XRIQuery query = new XRIQuery();
if (query.scan(oStream))
{
this.query = query;
}
XRIFragment fragment = new XRIFragment();
if (fragment.scan(oStream))
{
this.fragment = fragment;
}
return true;
}
public AuthorityPath AuthorityPath
{
get
{
return moAuthorityPath;
}
}
public XRIPath XRIPath
{
get
{
return moAbsolutePath;
}
}
/// <summary>
/// Returns the query.
/// </summary>
public XRIQuery Query
{
get
{
return query;
}
}
/// <summary>
/// Returns the fragment.
/// </summary>
public XRIFragment Fragment
{
get
{
return fragment;
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Simple.OData.Client.Office365.ExampleA
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// </summary>
/// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns>
public string GetDatabaseConnectionString()
{
string dbConnectionString = null;
using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost())
{
if (clientContext != null)
{
var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext);
clientContext.ExecuteQuery();
dbConnectionString = result.Value;
}
}
if (dbConnectionString == null)
{
const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging";
var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey];
dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null;
}
return dbConnectionString;
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
using System.Threading;
using ICSharpCode.NRefactory6.CSharp.Refactoring;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Linq;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.FindSymbols;
namespace ICSharpCode.NRefactory6.CSharp.Diagnostics
{
[DiagnosticAnalyzer]
[ExportDiagnosticAnalyzer("", LanguageNames.CSharp)]
[NRefactoryCodeDiagnosticAnalyzer(Description = "", AnalysisDisableKeyword = "")]
[IssueDescription("Use of Linq methods when there's a better alternative",
Description = "Detects usage of Linq when there's a simpler and faster alternative",
Category = IssueCategories.CodeQualityIssues,
Severity = Severity.Warning)]
public class DontUseLinqWhenItsVerboseAndInefficientDiagnosticAnalyzer : GatherVisitorCodeIssueProvider
{
class LinqMethod
{
internal string FullName;
internal bool IsLast;
/// <summary>
/// Indicates that the method should be considered bad even when used alone.
/// </summary>
internal bool IsPoorStyleAlone;
/// <summary>
/// The number of parameters the definition has.
/// </summary>
internal int ParameterCount;
}
static readonly List<LinqMethod> LinqMethods = new List<LinqMethod> {
new LinqMethod { FullName = "System.Linq.Enumerable.First", IsLast = true, ParameterCount = 1, IsPoorStyleAlone = true },
new LinqMethod { FullName = "System.Linq.Enumerable.Last", IsLast = true, ParameterCount = 1 },
new LinqMethod { FullName = "System.Linq.Enumerable.ElementAt", IsLast = true, ParameterCount = 2, IsPoorStyleAlone = true },
new LinqMethod { FullName = "System.Linq.Enumerable.Count", IsLast = true, ParameterCount = 1, IsPoorStyleAlone = true },
new LinqMethod { FullName = "System.Linq.Enumerable.Any", IsLast = true, ParameterCount = 1 },
new LinqMethod { FullName = "System.Linq.Enumerable.Skip", ParameterCount = 2 },
//Take(n) is problematic -- it has a weird behavior if n > Count()
//new LinqMethod { FullName = "System.Linq.Enumerable.Take", ParameterCount = 2 },
new LinqMethod { FullName = "System.Linq.Enumerable.Reverse", ParameterCount = 1 }
};
internal const string DiagnosticId = "";
const string Description = "";
const string MessageFormat = "";
const string Category = IssueCategories.CodeQualityIssues;
static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Description, MessageFormat, Category, DiagnosticSeverity.Warning);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
protected override CSharpSyntaxWalker CreateVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
{
return new GatherVisitor(semanticModel, addDiagnostic, cancellationToken);
}
class GatherVisitor : GatherVisitorBase<DontUseLinqWhenItsVerboseAndInefficientIssue>
{
public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
: base(semanticModel, addDiagnostic, cancellationToken)
{
}
public override void VisitInvocationExpression(InvocationExpression invocationExpression)
{
InvocationExpression outerInvocationExpression = invocationExpression;
//Note the invocations are in reverse order, so x.Foo().Bar() will have [0] be the Bar() and [1] be the Foo()
List<InvocationExpression> invocations = new List<InvocationExpression>();
LinqMethod outerMethod = null;
Expression target = null;
for (; ;)
{
var resolveResult = ctx.Resolve(invocationExpression) as MemberResolveResult;
if (resolveResult == null || !(resolveResult.Member is IMethod))
{
break;
}
var method = LinqMethods.FirstOrDefault(candidate => candidate.FullName == resolveResult.Member.FullName &&
candidate.ParameterCount == ((IMethod)resolveResult.Member.MemberDefinition).Parameters.Count);
if (method == null || (invocations.Any() && method.IsLast))
{
break;
}
var mre = invocationExpression.Target as MemberReferenceExpression;
if (mre == null)
{
break;
}
if (outerMethod == null)
{
outerMethod = method;
}
invocations.Add(invocationExpression);
target = mre.Target;
var newInvocation = target as InvocationExpression;
if (newInvocation == null)
{
break;
}
invocationExpression = newInvocation;
}
if (target == null)
{
base.VisitInvocationExpression(invocationExpression);
return;
}
if (!outerMethod.IsPoorStyleAlone && invocations.Count == 1)
{
base.VisitInvocationExpression(invocationExpression);
return;
}
var currentTypeDeclaration = outerInvocationExpression.GetParent<TypeDeclaration>();
var currentTypeResolveResult = ctx.Resolve(currentTypeDeclaration) as TypeResolveResult;
if (currentTypeResolveResult == null)
{
base.VisitInvocationExpression(invocationExpression);
return;
}
var currentTypeDefinition = currentTypeResolveResult.Type.GetDefinition();
var targetResolveResult = ctx.Resolve(target);
if (!CanIndex(currentTypeDefinition, targetResolveResult))
{
base.VisitInvocationExpression(invocationExpression);
return;
}
string countPropertyName = GetCountProperty(currentTypeDefinition, targetResolveResult);
string lastInvocationName = ((MemberReferenceExpression)invocations[0].Target).MemberName;
bool endsReversed = invocations.Count(invocation => ((MemberReferenceExpression)invocation.Target).MemberName == "Reverse") % 2 != 0;
bool requiresCount = lastInvocationName == "Count" || lastInvocationName == "Any" ||
(endsReversed ? lastInvocationName == "First" || lastInvocationName == "ElementAt" : lastInvocationName == "Last");
if (countPropertyName == null && requiresCount)
{
base.VisitInvocationExpression(invocationExpression);
return;
}
AddDiagnosticAnalyzer(new CodeIssue(invocations.Last().LParToken.StartLocation,
invocations.First().RParToken.EndLocation,
ctx.TranslateString("Use of Linq method when there's a better alternative"),
ctx.TranslateString("Replace method by simpler version"),
script =>
{
Expression startOffset = null;
Expression endOffset = null;
bool reversed = false;
foreach (var invocation in invocations.AsEnumerable().Reverse())
{
string invocationName = ((MemberReferenceExpression)invocation.Target).MemberName;
switch (invocationName)
{
case "Skip":
Expression offset = reversed ? endOffset : startOffset;
if (offset == null)
offset = invocation.Arguments.Last().Clone();
else
offset = new BinaryOperatorExpression(offset,
BinaryOperatorType.Add,
invocation.Arguments.Last().Clone());
if (reversed)
endOffset = offset;
else
startOffset = offset;
break;
case "Reverse":
reversed = !reversed;
break;
case "First":
case "ElementAt":
case "Last":
{
bool fromEnd = (invocationName == "Last") ^ reversed;
Expression index = invocationName == "ElementAt" ? invocation.Arguments.Last().Clone() : null;
Expression baseOffset = fromEnd ? endOffset : startOffset;
//Our indexWithOffset is baseOffset + index
//A baseOffset/index of null is considered "0".
Expression indexWithOffset = baseOffset == null ? index :
index == null ? baseOffset :
new BinaryOperatorExpression(baseOffset, BinaryOperatorType.Add, index);
Expression indexerExpression = indexWithOffset;
if (fromEnd)
{
var endExpression = new BinaryOperatorExpression(new MemberReferenceExpression(target.Clone(), countPropertyName),
BinaryOperatorType.Subtract,
new PrimitiveExpression(1));
if (indexerExpression == null)
{
indexerExpression = endExpression;
}
else
{
indexerExpression = new BinaryOperatorExpression(endExpression,
BinaryOperatorType.Subtract,
new ParenthesizedExpression(indexerExpression));
}
}
indexerExpression = indexerExpression ?? new PrimitiveExpression(0);
var newExpression = new IndexerExpression(target.Clone(),
indexerExpression);
script.Replace(outerInvocationExpression, newExpression);
break;
}
case "Count":
case "Any":
{
Expression takenMembers;
if (startOffset == null)
{
takenMembers = endOffset;
}
else if (endOffset == null)
{
takenMembers = startOffset;
}
else
{
takenMembers = new BinaryOperatorExpression(startOffset,
BinaryOperatorType.Add,
endOffset);
}
var countExpression = new MemberReferenceExpression(target.Clone(), countPropertyName);
Expression newExpression;
if (invocationName == "Count")
{
if (takenMembers == null)
newExpression = countExpression;
else
newExpression = new BinaryOperatorExpression(countExpression,
BinaryOperatorType.Subtract,
new ParenthesizedExpression(takenMembers));
}
else
{
newExpression = new BinaryOperatorExpression(countExpression,
BinaryOperatorType.GreaterThan,
new ParenthesizedExpression(takenMembers));
}
script.Replace(outerInvocationExpression, newExpression);
break;
}
}
}
}));
base.VisitInvocationExpression(invocationExpression);
}
bool CanIndex(ITypeDefinition currentTypeDefinition, ResolveResult targetResolveResult)
{
if (targetResolveResult.Type is ArrayType)
{
return true;
}
var memberLookup = new MemberLookup(currentTypeDefinition, ctx.Compilation.MainAssembly);
var indexers = memberLookup.LookupIndexers(targetResolveResult).ToList();
return indexers.SelectMany(methodList => methodList).Any(
member => ((IProperty)member).CanGet && ((IProperty)member).Getter.Parameters.Count == 1);
}
string GetCountProperty(ITypeDefinition currentTypeDefinition, ResolveResult targetResolveResult)
{
var memberLookup = new MemberLookup(currentTypeDefinition, ctx.Compilation.MainAssembly);
string countProperty = TryProperty(memberLookup, targetResolveResult, "Count");
if (countProperty != null)
{
return countProperty;
}
return TryProperty(memberLookup, targetResolveResult, "Length");
}
string TryProperty(MemberLookup memberLookup, ResolveResult targetResolveResult, string name)
{
var countResolveResult = memberLookup.Lookup(targetResolveResult, name, EmptyList<IType>.Instance, false);
var countPropertyResolveResult = countResolveResult as MemberResolveResult;
if (countPropertyResolveResult == null)
{
return null;
}
var property = countPropertyResolveResult.Member as IProperty;
if (property == null || !property.CanGet)
{
return null;
}
return name;
}
}
}
[ExportCodeFixProvider(.DiagnosticId, LanguageNames.CSharp)]
public class FixProvider : ICodeFixProvider
{
public IEnumerable<string> GetFixableDiagnosticIds()
{
yield return .DiagnosticId;
}
public async Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, TextSpan span, IEnumerable<Diagnostic> diagnostics, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var result = new List<CodeAction>();
foreach (var diagonstic in diagnostics)
{
var node = root.FindNode(diagonstic.Location.SourceSpan);
//if (!node.IsKind(SyntaxKind.BaseList))
// continue;
var newRoot = root.RemoveNode(node, SyntaxRemoveOptions.KeepNoTrivia);
result.Add(CodeActionFactory.Create(node.Span, diagonstic.Severity, diagonstic.GetMessage(), document.WithSyntaxRoot(newRoot)));
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class PfxTests
{
public static IEnumerable<object[]> BrainpoolCurvesPfx
{
get
{
#if NETNATIVE
yield break;
#else
yield return new object[] { TestData.ECDsabrainpoolP160r1_Pfx };
yield return new object[] { TestData.ECDsabrainpoolP160r1_Explicit_Pfx };
#endif
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void TestConstructor(X509KeyStorageFlags keyStorageFlags)
{
using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
byte[] expectedThumbprint = "71cb4e2b02738ad44f8b382c93bd17ba665f9914".HexToByteArray();
string subject = c.Subject;
Assert.Equal("CN=MyName", subject);
byte[] thumbPrint = c.GetCertHash();
Assert.Equal(expectedThumbprint, thumbPrint);
}
}
#if netcoreapp
[Theory]
[MemberData(nameof(StorageFlags))]
public static void TestConstructor_SecureString(X509KeyStorageFlags keyStorageFlags)
{
using (SecureString password = TestData.CreatePfxDataPasswordSecureString())
using (var c = new X509Certificate2(TestData.PfxData, password, keyStorageFlags))
{
byte[] expectedThumbprint = "71cb4e2b02738ad44f8b382c93bd17ba665f9914".HexToByteArray();
string subject = c.Subject;
Assert.Equal("CN=MyName", subject);
byte[] thumbPrint = c.GetCertHash();
Assert.Equal(expectedThumbprint, thumbPrint);
}
}
#endif
[Theory]
[MemberData(nameof(StorageFlags))]
public static void EnsurePrivateKeyPreferred(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.ChainPfxBytes, TestData.ChainPfxPassword, keyStorageFlags))
{
// While checking cert.HasPrivateKey first is most matching of the test description, asserting
// on the certificate's simple name will provide a more diagnosable failure.
Assert.Equal("test.local", cert.GetNameInfo(X509NameType.SimpleName, false));
Assert.True(cert.HasPrivateKey, "cert.HasPrivateKey");
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void TestRawData(X509KeyStorageFlags keyStorageFlags)
{
byte[] expectedRawData = (
"308201e530820152a0030201020210d5b5bc1c458a558845" +
"bff51cb4dff31c300906052b0e03021d05003011310f300d" +
"060355040313064d794e616d65301e170d31303034303130" +
"38303030305a170d3131303430313038303030305a301131" +
"0f300d060355040313064d794e616d6530819f300d06092a" +
"864886f70d010101050003818d0030818902818100b11e30" +
"ea87424a371e30227e933ce6be0e65ff1c189d0d888ec8ff" +
"13aa7b42b68056128322b21f2b6976609b62b6bc4cf2e55f" +
"f5ae64e9b68c78a3c2dacc916a1bc7322dd353b32898675c" +
"fb5b298b176d978b1f12313e3d865bc53465a11cca106870" +
"a4b5d50a2c410938240e92b64902baea23eb093d9599e9e3" +
"72e48336730203010001a346304430420603551d01043b30" +
"39801024859ebf125e76af3f0d7979b4ac7a96a113301131" +
"0f300d060355040313064d794e616d658210d5b5bc1c458a" +
"558845bff51cb4dff31c300906052b0e03021d0500038181" +
"009bf6e2cf830ed485b86d6b9e8dffdcd65efc7ec145cb93" +
"48923710666791fcfa3ab59d689ffd7234b7872611c5c23e" +
"5e0714531abadb5de492d2c736e1c929e648a65cc9eb63cd" +
"84e57b5909dd5ddf5dbbba4a6498b9ca225b6e368b94913b" +
"fc24de6b2bd9a26b192b957304b89531e902ffc91b54b237" +
"bb228be8afcda26476").HexToByteArray();
using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
byte[] rawData = c.RawData;
Assert.Equal(expectedRawData, rawData);
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void TestPrivateKey(X509KeyStorageFlags keyStorageFlags)
{
using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, keyStorageFlags))
{
bool hasPrivateKey = c.HasPrivateKey;
Assert.True(hasPrivateKey);
using (RSA rsa = c.GetRSAPrivateKey())
{
VerifyPrivateKey(rsa);
}
}
}
#if netcoreapp
[Fact]
public static void TestPrivateKeyProperty()
{
using (var c = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.EphemeralKeySet))
{
bool hasPrivateKey = c.HasPrivateKey;
Assert.True(hasPrivateKey);
AsymmetricAlgorithm alg = c.PrivateKey;
Assert.NotNull(alg);
Assert.Same(alg, c.PrivateKey);
Assert.IsAssignableFrom(typeof(RSA), alg);
VerifyPrivateKey((RSA)alg);
// Currently unable to set PrivateKey
Assert.Throws<PlatformNotSupportedException>(() => c.PrivateKey = null);
Assert.Throws<PlatformNotSupportedException>(() => c.PrivateKey = alg);
}
}
#endif
private static void VerifyPrivateKey(RSA rsa)
{
byte[] hash = new byte[20];
byte[] sig = rsa.SignHash(hash, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
Assert.Equal(TestData.PfxSha1Empty_ExpectedSig, sig);
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ExportWithPrivateKey(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.Exportable | keyStorageFlags))
{
const string password = "NotVerySecret";
byte[] pkcs12 = cert.Export(X509ContentType.Pkcs12, password);
using (var certFromPfx = new X509Certificate2(pkcs12, password, keyStorageFlags))
{
Assert.True(certFromPfx.HasPrivateKey);
Assert.Equal(cert, certFromPfx);
}
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ReadECDsaPrivateKey_WindowsPfx(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test", keyStorageFlags))
{
using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
{
Verify_ECDsaPrivateKey_WindowsPfx(ecdsa);
}
}
}
#if netcoreapp
[Fact]
public static void ECDsaPrivateKeyProperty_WindowsPfx()
{
using (var cert = new X509Certificate2(TestData.ECDsaP256_DigitalSignature_Pfx_Windows, "Test", X509KeyStorageFlags.EphemeralKeySet))
{
AsymmetricAlgorithm alg = cert.PrivateKey;
Assert.NotNull(alg);
Assert.Same(alg, cert.PrivateKey);
Assert.IsAssignableFrom(typeof(ECDsa), alg);
Verify_ECDsaPrivateKey_WindowsPfx((ECDsa)alg);
// Currently unable to set PrivateKey
Assert.Throws<PlatformNotSupportedException>(() => cert.PrivateKey = null);
Assert.Throws<PlatformNotSupportedException>(() => cert.PrivateKey = alg);
}
}
#endif
private static void Verify_ECDsaPrivateKey_WindowsPfx(ECDsa ecdsa)
{
Assert.NotNull(ecdsa);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
AssertEccAlgorithm(ecdsa, "ECDSA_P256");
}
}
[Theory, MemberData(nameof(BrainpoolCurvesPfx))]
public static void ReadECDsaPrivateKey_BrainpoolP160r1_Pfx(byte[] pfxData)
{
try
{
using (var cert = new X509Certificate2(pfxData, TestData.PfxDataPassword))
{
using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
{
Assert.NotNull(ecdsa);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
AssertEccAlgorithm(ecdsa, "ECDH");
}
}
}
}
catch (CryptographicException)
{
// Windows 7, Windows 8, Ubuntu 14, CentOS can fail. Verify known good platforms don't fail.
Assert.False(PlatformDetection.IsWindows && PlatformDetection.WindowsVersion >= 10);
Assert.False(PlatformDetection.IsUbuntu1604);
Assert.False(PlatformDetection.IsUbuntu1610);
Assert.False(PlatformDetection.IsOSX);
return;
}
}
[Theory]
[MemberData(nameof(StorageFlags))]
public static void ReadECDsaPrivateKey_OpenSslPfx(X509KeyStorageFlags keyStorageFlags)
{
using (var cert = new X509Certificate2(TestData.ECDsaP256_DigitalSignature_Pfx_OpenSsl, "Test", keyStorageFlags))
using (ECDsa ecdsa = cert.GetECDsaPrivateKey())
{
Assert.NotNull(ecdsa);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// If Windows were to start detecting this case as ECDSA that wouldn't be bad,
// but this assert is the only proof that this certificate was made with OpenSSL.
//
// Windows ECDSA PFX files contain metadata in the private key keybag which identify it
// to Windows as ECDSA. OpenSSL doesn't have anywhere to persist that data when
// extracting it to the key PEM file, and so no longer has it when putting the PFX
// together. But, it also wouldn't have had the Windows-specific metadata when the
// key was generated on the OpenSSL side in the first place.
//
// So, again, it's not important that Windows "mis-detects" this as ECDH. What's
// important is that we were able to create an ECDsa object from it.
AssertEccAlgorithm(ecdsa, "ECDH_P256");
}
}
}
#if netcoreapp
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void EphemeralImport_HasNoKeyName()
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.EphemeralKeySet))
using (RSA rsa = cert.GetRSAPrivateKey())
{
Assert.NotNull(rsa);
// While RSACng is not a guaranteed answer, it's currently the answer and we'd have to
// rewrite the rest of this test if it changed.
RSACng rsaCng = rsa as RSACng;
Assert.NotNull(rsaCng);
CngKey key = rsaCng.Key;
Assert.NotNull(key);
Assert.True(key.IsEphemeral, "key.IsEphemeral");
Assert.Null(key.KeyName);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void CollectionEphemeralImport_HasNoKeyName()
{
using (var importedCollection = Cert.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.EphemeralKeySet))
{
X509Certificate2 cert = importedCollection.Collection[0];
using (RSA rsa = cert.GetRSAPrivateKey())
{
Assert.NotNull(rsa);
// While RSACng is not a guaranteed answer, it's currently the answer and we'd have to
// rewrite the rest of this test if it changed.
RSACng rsaCng = rsa as RSACng;
Assert.NotNull(rsaCng);
CngKey key = rsaCng.Key;
Assert.NotNull(key);
Assert.True(key.IsEphemeral, "key.IsEphemeral");
Assert.Null(key.KeyName);
}
}
}
#endif
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void PerphemeralImport_HasKeyName()
{
using (var cert = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet))
using (RSA rsa = cert.GetRSAPrivateKey())
{
Assert.NotNull(rsa);
// While RSACng is not a guaranteed answer, it's currently the answer and we'd have to
// rewrite the rest of this test if it changed.
RSACng rsaCng = rsa as RSACng;
Assert.NotNull(rsaCng);
CngKey key = rsaCng.Key;
Assert.NotNull(key);
Assert.False(key.IsEphemeral, "key.IsEphemeral");
Assert.NotNull(key.KeyName);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes
public static void CollectionPerphemeralImport_HasKeyName()
{
using (var importedCollection = Cert.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet))
{
X509Certificate2 cert = importedCollection.Collection[0];
using (RSA rsa = cert.GetRSAPrivateKey())
{
Assert.NotNull(rsa);
// While RSACng is not a guaranteed answer, it's currently the answer and we'd have to
// rewrite the rest of this test if it changed.
RSACng rsaCng = rsa as RSACng;
Assert.NotNull(rsaCng);
CngKey key = rsaCng.Key;
Assert.NotNull(key);
Assert.False(key.IsEphemeral, "key.IsEphemeral");
Assert.NotNull(key.KeyName);
}
}
}
// Keep the ECDsaCng-ness contained within this helper method so that it doesn't trigger a
// FileNotFoundException on Unix.
private static void AssertEccAlgorithm(ECDsa ecdsa, string algorithmId)
{
ECDsaCng cng = ecdsa as ECDsaCng;
if (cng != null)
{
Assert.Equal(algorithmId, cng.Key.Algorithm.Algorithm);
}
}
public static IEnumerable<object[]> StorageFlags
{
get
{
yield return new object[] { X509KeyStorageFlags.DefaultKeySet };
#if netcoreapp
yield return new object[] { X509KeyStorageFlags.EphemeralKeySet };
#endif
}
}
private static X509Certificate2 Rewrap(this X509Certificate2 c)
{
X509Certificate2 newC = new X509Certificate2(c.Handle);
c.Dispose();
return newC;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Gui;
using System.Reflection;
using FlatRedBall.IO;
using System.Collections;
namespace XmlObjectEditor.Gui
{
public static class GuiData
{
#region Fields
static ListDisplayWindow mAssembliesListDisplayWindow;
static ListDisplayWindow mAssemblyTypeListDisplayWindow;
static Type mTypeOfObjectToSerialize;
static object mObjectToSerialize = null;
// Since the type isn't known for the PropertyGrid, the only way to
// change the reference when loading an object is to recreate the PropertyGrid.
// When this is done the old PropertyGrid must be destroyed and the new one must
// be created. To do this the old PropertyGrid reference must be held.
static PropertyGrid mObjectPropertyGrid;
// If the object is an IList, then use a ListDisplayWindow.
static ListDisplayWindow mObjectListDisplayWindow;
#endregion
#region Event Methods
private static void CreateObjectOfSelectedType(Window callingWindow)
{
CollapseListBox collapseListBox = callingWindow as CollapseListBox;
Type type = collapseListBox.GetFirstHighlightedObject() as Type;
mObjectToSerialize = Activator.CreateInstance(type);
mTypeOfObjectToSerialize = type;
if (PropertyGrid.IsIEnumerable(type))
{
mObjectListDisplayWindow = CreateListDisplayWindowForObject(mObjectToSerialize);
}
else
{
mObjectPropertyGrid = CreatePropertyGridForObject(mObjectToSerialize);
}
}
private static void ClickShowAssemblyTypes(Window callingWindow)
{
mAssemblyTypeListDisplayWindow.Visible = true;
GuiManager.BringToFront(mAssemblyTypeListDisplayWindow);
mAssemblyTypeListDisplayWindow.ListShowing = EditorData.EditorLogic.CurrentAssembly.GetTypes();
}
private static PropertyGrid CreatePropertyGridForObject(object objectToCreateGridFor)
{
object[] arguments = new object[]{
GuiManager.Cursor,
objectToCreateGridFor
};
Type t = typeof(PropertyGrid<>).MakeGenericType(mTypeOfObjectToSerialize);
object obj = Activator.CreateInstance(t, arguments);
PropertyGrid propertyGrid = obj as PropertyGrid;
GuiManager.AddWindow(propertyGrid);
propertyGrid.HasCloseButton = true;
propertyGrid.Closing += GuiManager.RemoveWindow;
Button saveButton = new Button(GuiManager.Cursor);
saveButton.Text = "Save Object as XML";
saveButton.ScaleX = 9f;
saveButton.Click += XmlSeralizeObject;
propertyGrid.AddWindow(saveButton);
Button loadButton = new Button(GuiManager.Cursor);
loadButton.Text = "Load Object from XML";
loadButton.ScaleX = 9f;
loadButton.Click += XmlDeserializeObject;
propertyGrid.AddWindow(loadButton);
return propertyGrid;
}
private static ListDisplayWindow CreateListDisplayWindowForObject(object objectToCreateWindowFor)
{
ListDisplayWindow listDisplayWindow = new ListDisplayWindow(GuiManager.Cursor);
GuiManager.AddWindow(listDisplayWindow);
listDisplayWindow.HasMoveBar = true;
listDisplayWindow.HasCloseButton = true;
listDisplayWindow.Resizable = true;
listDisplayWindow.ListShowing = mObjectToSerialize as IEnumerable;
listDisplayWindow.Closing += GuiManager.RemoveWindow;
// listDisplayWindow.EnableAddingToList();
Button saveButton = new Button(GuiManager.Cursor);
saveButton.Text = "Save Object as XML";
saveButton.ScaleX = 9f;
saveButton.Click += XmlSeralizeObject;
listDisplayWindow.AddWindow(saveButton);
Button loadButton = new Button(GuiManager.Cursor);
loadButton.Text = "Load Object from XML";
loadButton.ScaleX = 9f;
loadButton.Click += XmlDeserializeObject;
listDisplayWindow.AddWindow(loadButton);
listDisplayWindow.MinimumScaleX = 10;
return listDisplayWindow;
}
static void HighlightNewAssembly(Window callingWindow)
{
EditorData.EditorLogic.CurrentAssembly = mAssembliesListDisplayWindow.GetFirstHighlightedObject() as Assembly;
}
private static void LoadAssembly(Window callingWindow)
{
FileWindow fileWindow = GuiManager.AddFileWindow();
fileWindow.SetToLoad();
fileWindow.Filter =
"Executable (*.exe)|*.exe|DLL (*.dll)|*.dll";
fileWindow.OkClick += LoadAssemblyOk;
}
private static void LoadAssemblyOk(Window callingWindow)
{
EditorData.LoadAssembly(((FileWindow)callingWindow).Results[0]);
}
private static void ShowAssemblyPropertyGrid(Window callingWindow)
{
PropertyGrid<Assembly> propertyGrid = callingWindow as PropertyGrid<Assembly>;
//EditorData.EditorLogic.CurrentAssembly = propertyGrid.SelectedObject;
Button showTypes = new Button(GuiManager.Cursor);
showTypes.Text = "Show Types";
showTypes.ScaleX = 5;
showTypes.Click += ClickShowAssemblyTypes;
propertyGrid.AddWindow(showTypes);
}
private static void XmlDeserializeObject(Window callingWindow)
{
FileWindow fileWindow = GuiManager.AddFileWindow();
fileWindow.SetToLoad();
fileWindow.SetFileType("xml");
fileWindow.OkClick += XmlDeserializeObjectOk;
}
private static void XmlDeserializeObjectOk(Window callingWindow)
{
mObjectToSerialize = FileManager.XmlDeserialize(mTypeOfObjectToSerialize,
((FileWindow)callingWindow).Results[0]);
if (mObjectPropertyGrid != null)
GuiManager.RemoveWindow(mObjectPropertyGrid);
PropertyGrid newPropertyGrid = CreatePropertyGridForObject(mObjectToSerialize);
newPropertyGrid.X = mObjectPropertyGrid.X;
newPropertyGrid.Y = mObjectPropertyGrid.Y;
mObjectPropertyGrid = newPropertyGrid;
}
private static void XmlSeralizeObject(Window callingWindow)
{
FileWindow fileWindow = GuiManager.AddFileWindow();
fileWindow.SetToSave();
fileWindow.SetFileType("xml");
fileWindow.OkClick += XmlSerializeObjectOk;
}
private static void XmlSerializeObjectOk(Window callingWindow)
{
FileManager.XmlSerialize(
mTypeOfObjectToSerialize,
mObjectToSerialize,
((FileWindow)callingWindow).Results[0]);
}
#endregion
#region Methods
#region Public Methods
public static void Initialize()
{
CreateMenuStrip();
CreateListDisplayWindows();
CreatePropertyGrids();
}
public static void Update()
{
mAssembliesListDisplayWindow.UpdateToList();
if (mObjectListDisplayWindow != null)
{
mObjectListDisplayWindow.UpdateToList();
}
if(mObjectPropertyGrid != null)
{
mObjectPropertyGrid.UpdateDisplayedProperties();
}
}
#endregion
#region Private Methods
private static void CreateListDisplayWindows()
{
mAssembliesListDisplayWindow = new ListDisplayWindow(GuiManager.Cursor);
GuiManager.AddWindow(mAssembliesListDisplayWindow);
mAssembliesListDisplayWindow.ScaleX = 10;
mAssembliesListDisplayWindow.ScaleY = 12;
mAssembliesListDisplayWindow.HasMoveBar = true;
mAssembliesListDisplayWindow.X = mAssembliesListDisplayWindow.ScaleX;
mAssembliesListDisplayWindow.Y = mAssembliesListDisplayWindow.ScaleY + 6;
mAssembliesListDisplayWindow.Resizable = true;
mAssembliesListDisplayWindow.ShowPropertyGridOnStrongSelect = true;
mAssembliesListDisplayWindow.ListBox.Highlight += HighlightNewAssembly;
mAssembliesListDisplayWindow.ListShowing = EditorData.Assemblies;
mAssemblyTypeListDisplayWindow = new ListDisplayWindow(GuiManager.Cursor);
mAssemblyTypeListDisplayWindow.Visible = false;
GuiManager.AddWindow(mAssemblyTypeListDisplayWindow);
mAssemblyTypeListDisplayWindow.ScaleX = 10;
mAssemblyTypeListDisplayWindow.ScaleY = 12;
mAssemblyTypeListDisplayWindow.HasMoveBar = true;
mAssemblyTypeListDisplayWindow.X = mAssembliesListDisplayWindow.ScaleX;
mAssemblyTypeListDisplayWindow.Y = 26;
mAssemblyTypeListDisplayWindow.Resizable = true;
mAssemblyTypeListDisplayWindow.ListBox.StrongSelect += CreateObjectOfSelectedType;
mAssemblyTypeListDisplayWindow.HasCloseButton = true;
}
private static void CreateMenuStrip()
{
MenuStrip menuStrip = GuiManager.AddMenuStrip();
MenuItem menuItem = menuStrip.AddItem("File");
menuItem.AddItem("Load Assembly").Click += LoadAssembly;
}
private static void CreatePropertyGrids()
{
PropertyGrid.SetNewWindowEvent(typeof(Assembly), ShowAssemblyPropertyGrid);
}
#endregion
#endregion
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Platform;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Collections;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets;
using osu.Game.Screens.Select;
using osu.Game.Tests.Resources;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
public class TestSceneFilterControl : OsuManualInputManagerTestScene
{
protected override Container<Drawable> Content { get; } = new Container { RelativeSizeAxes = Axes.Both };
private CollectionManager collectionManager;
private RulesetStore rulesets;
private BeatmapManager beatmapManager;
private FilterControl control;
[BackgroundDependencyLoader]
private void load(GameHost host)
{
Dependencies.Cache(rulesets = new RulesetStore(ContextFactory));
Dependencies.Cache(beatmapManager = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, Audio, Resources, host, Beatmap.Default));
beatmapManager.Import(TestResources.GetQuickTestBeatmapForImport()).Wait();
base.Content.AddRange(new Drawable[]
{
collectionManager = new CollectionManager(LocalStorage),
Content
});
Dependencies.Cache(collectionManager);
}
[SetUp]
public void SetUp() => Schedule(() =>
{
collectionManager.Collections.Clear();
Child = control = new FilterControl
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = FilterControl.HEIGHT,
};
});
[Test]
public void TestEmptyCollectionFilterContainsAllBeatmaps()
{
assertCollectionDropdownContains("All beatmaps");
assertCollectionHeaderDisplays("All beatmaps");
}
[Test]
public void TestCollectionAddedToDropdown()
{
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "2" } }));
assertCollectionDropdownContains("1");
assertCollectionDropdownContains("2");
}
[Test]
public void TestCollectionRemovedFromDropdown()
{
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "2" } }));
AddStep("remove collection", () => collectionManager.Collections.RemoveAt(0));
assertCollectionDropdownContains("1", false);
assertCollectionDropdownContains("2");
}
[Test]
public void TestCollectionRenamed()
{
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("select collection", () =>
{
var dropdown = control.ChildrenOfType<CollectionFilterDropdown>().Single();
dropdown.Current.Value = dropdown.ItemSource.ElementAt(1);
});
addExpandHeaderStep();
AddStep("change name", () => collectionManager.Collections[0].Name.Value = "First");
assertCollectionDropdownContains("First");
assertCollectionHeaderDisplays("First");
}
[Test]
public void TestAllBeatmapFilterDoesNotHaveAddButton()
{
addExpandHeaderStep();
AddStep("hover all beatmaps", () => InputManager.MoveMouseTo(getAddOrRemoveButton(0)));
AddAssert("'All beatmaps' filter does not have add button", () => !getAddOrRemoveButton(0).IsPresent);
}
[Test]
public void TestCollectionFilterHasAddButton()
{
addExpandHeaderStep();
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("hover collection", () => InputManager.MoveMouseTo(getAddOrRemoveButton(1)));
AddAssert("collection has add button", () => getAddOrRemoveButton(1).IsPresent);
}
[Test]
public void TestButtonDisabledAndEnabledWithBeatmapChanges()
{
addExpandHeaderStep();
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0]));
AddAssert("button enabled", () => getAddOrRemoveButton(1).Enabled.Value);
AddStep("set dummy beatmap", () => Beatmap.SetDefault());
AddAssert("button disabled", () => !getAddOrRemoveButton(1).Enabled.Value);
}
[Test]
public void TestButtonChangesWhenAddedAndRemovedFromCollection()
{
addExpandHeaderStep();
AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0]));
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare));
AddStep("add beatmap to collection", () => collectionManager.Collections[0].Beatmaps.Add(Beatmap.Value.BeatmapInfo));
AddAssert("button is minus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.MinusSquare));
AddStep("remove beatmap from collection", () => collectionManager.Collections[0].Beatmaps.Clear());
AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare));
}
[Test]
public void TestButtonAddsAndRemovesBeatmap()
{
addExpandHeaderStep();
AddStep("select available beatmap", () => Beatmap.Value = beatmapManager.GetWorkingBeatmap(beatmapManager.GetAllUsableBeatmapSets().First().Beatmaps[0]));
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare));
addClickAddOrRemoveButtonStep(1);
AddAssert("collection contains beatmap", () => collectionManager.Collections[0].Beatmaps.Contains(Beatmap.Value.BeatmapInfo));
AddAssert("button is minus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.MinusSquare));
addClickAddOrRemoveButtonStep(1);
AddAssert("collection does not contain beatmap", () => !collectionManager.Collections[0].Beatmaps.Contains(Beatmap.Value.BeatmapInfo));
AddAssert("button is plus", () => getAddOrRemoveButton(1).Icon.Equals(FontAwesome.Solid.PlusSquare));
}
[Test]
public void TestManageCollectionsFilterIsNotSelected()
{
addExpandHeaderStep();
AddStep("add collection", () => collectionManager.Collections.Add(new BeatmapCollection { Name = { Value = "1" } }));
AddStep("select collection", () =>
{
InputManager.MoveMouseTo(getCollectionDropdownItems().ElementAt(1));
InputManager.Click(MouseButton.Left);
});
addExpandHeaderStep();
AddStep("click manage collections filter", () =>
{
InputManager.MoveMouseTo(getCollectionDropdownItems().Last());
InputManager.Click(MouseButton.Left);
});
AddAssert("collection filter still selected", () => control.CreateCriteria().Collection?.Name.Value == "1");
}
private void assertCollectionHeaderDisplays(string collectionName, bool shouldDisplay = true)
=> AddAssert($"collection dropdown header displays '{collectionName}'",
() => shouldDisplay == (control.ChildrenOfType<CollectionFilterDropdown.CollectionDropdownHeader>().Single().ChildrenOfType<SpriteText>().First().Text == collectionName));
private void assertCollectionDropdownContains(string collectionName, bool shouldContain = true) =>
AddAssert($"collection dropdown {(shouldContain ? "contains" : "does not contain")} '{collectionName}'",
// A bit of a roundabout way of going about this, see: https://github.com/ppy/osu-framework/issues/3871 + https://github.com/ppy/osu-framework/issues/3872
() => shouldContain == (getCollectionDropdownItems().Any(i => i.ChildrenOfType<FillFlowContainer>().OfType<IHasText>().First().Text == collectionName)));
private IconButton getAddOrRemoveButton(int index)
=> getCollectionDropdownItems().ElementAt(index).ChildrenOfType<IconButton>().Single();
private void addExpandHeaderStep() => AddStep("expand header", () =>
{
InputManager.MoveMouseTo(control.ChildrenOfType<CollectionFilterDropdown.CollectionDropdownHeader>().Single());
InputManager.Click(MouseButton.Left);
});
private void addClickAddOrRemoveButtonStep(int index) => AddStep("click add or remove button", () =>
{
InputManager.MoveMouseTo(getAddOrRemoveButton(index));
InputManager.Click(MouseButton.Left);
});
private IEnumerable<Dropdown<CollectionFilterMenuItem>.DropdownMenu.DrawableDropdownMenuItem> getCollectionDropdownItems()
=> control.ChildrenOfType<CollectionFilterDropdown>().Single().ChildrenOfType<Dropdown<CollectionFilterMenuItem>.DropdownMenu.DrawableDropdownMenuItem>();
}
}
| |
// 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 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// JobDetailsOperations operations.
/// </summary>
internal partial class JobDetailsOperations : IServiceOperations<RecoveryServicesBackupClient>, IJobDetailsOperations
{
/// <summary>
/// Initializes a new instance of the JobDetailsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal JobDetailsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Gets exteded information associated with the job.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='jobName'>
/// Name of the job whose details are to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string jobName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Cookie.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Cookie
{
/// <summary>
/// <para>This interface represents a <code>SetCookie2</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie2
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie2", AccessFlags = 1537)]
public partial interface ISetCookie2 : global::Org.Apache.Http.Cookie.ISetCookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// setCommentURL
/// </java-name>
[Dot42.DexImport("setCommentURL", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetCommentURL(string commentURL) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// setPorts
/// </java-name>
[Dot42.DexImport("setPorts", "([I)V", AccessFlags = 1025)]
void SetPorts(int[] ports) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Set the Discard attribute.</para><para>Note: <code>Discard</code> attribute overrides <code>Max-age</code>.</para><para><para>isPersistent() </para></para>
/// </summary>
/// <java-name>
/// setDiscard
/// </java-name>
[Dot42.DexImport("setDiscard", "(Z)V", AccessFlags = 1025)]
void SetDiscard(bool discard) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Signals that a cookie is in some way invalid or illegal in a given context</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/MalformedCookieException
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/MalformedCookieException", AccessFlags = 33)]
public partial class MalformedCookieException : global::Org.Apache.Http.ProtocolException
/* scope: __dot42__ */
{
/// <summary>
/// <para>Creates a new MalformedCookieException with a <code>null</code> detail message. </para>
/// </summary>
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public MalformedCookieException() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with a specified message string.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public MalformedCookieException(string message) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Creates a new MalformedCookieException with the specified detail message and cause.</para><para></para>
/// </summary>
[Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/lang/Throwable;)V", AccessFlags = 1)]
public MalformedCookieException(string message, global::System.Exception cause) /* MethodBuilder.Create */
{
}
}
/// <summary>
/// <para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecFactory
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecFactory", AccessFlags = 1537)]
public partial interface ICookieSpecFactory
/* scope: __dot42__ */
{
/// <java-name>
/// newInstance
/// </java-name>
[Dot42.DexImport("newInstance", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 1025)]
global::Org.Apache.Http.Cookie.ICookieSpec NewInstance(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Ths interface represents a cookie attribute handler responsible for parsing, validating, and matching a specific cookie attribute, such as path, domain, port, etc.</para><para>Different cookie specifications can provide a specific implementation for this class based on their cookie handling rules.</para><para><para> (Samit Jain)</para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieAttributeHandler
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieAttributeHandler", AccessFlags = 1537)]
public partial interface ICookieAttributeHandler
/* scope: __dot42__ */
{
/// <summary>
/// <para>Parse the given cookie attribute value and update the corresponding org.apache.http.cookie.Cookie property.</para><para></para>
/// </summary>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/cookie/SetCookie;Ljava/lang/String;)V", AccessFlags = 1025)]
void Parse(global::Org.Apache.Http.Cookie.ISetCookie cookie, string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Peforms cookie validation for the given attribute value.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Matches the given value (property of the destination host where request is being submitted) with the corresponding cookie attribute.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the match is successful; <code>false</code> otherwise </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP "magic-cookie" represents a piece of state information that the HTTP agent and the target server can exchange to maintain a session.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/Cookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/Cookie", AccessFlags = 1537)]
public partial interface ICookie
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the name.</para><para></para>
/// </summary>
/// <returns>
/// <para>String name The name </para>
/// </returns>
/// <java-name>
/// getName
/// </java-name>
[Dot42.DexImport("getName", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetName() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the value.</para><para></para>
/// </summary>
/// <returns>
/// <para>String value The current value. </para>
/// </returns>
/// <java-name>
/// getValue
/// </java-name>
[Dot42.DexImport("getValue", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetValue() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the comment describing the purpose of this cookie, or <code>null</code> if no such comment has been defined.</para><para></para>
/// </summary>
/// <returns>
/// <para>comment </para>
/// </returns>
/// <java-name>
/// getComment
/// </java-name>
[Dot42.DexImport("getComment", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetComment() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described by the information at this URL. </para>
/// </summary>
/// <java-name>
/// getCommentURL
/// </java-name>
[Dot42.DexImport("getCommentURL", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetCommentURL() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the expiration Date of the cookie, or <code>null</code> if none exists. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril. </para><para></para>
/// </summary>
/// <returns>
/// <para>Expiration Date, or <code>null</code>. </para>
/// </returns>
/// <java-name>
/// getExpiryDate
/// </java-name>
[Dot42.DexImport("getExpiryDate", "()Ljava/util/Date;", AccessFlags = 1025)]
global::Java.Util.Date GetExpiryDate() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns <code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>false</code> if the cookie should be discarded at the end of the "session"; <code>true</code> otherwise </para>
/// </returns>
/// <java-name>
/// isPersistent
/// </java-name>
[Dot42.DexImport("isPersistent", "()Z", AccessFlags = 1025)]
bool IsPersistent() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns domain attribute of the cookie.</para><para></para>
/// </summary>
/// <returns>
/// <para>the value of the domain attribute </para>
/// </returns>
/// <java-name>
/// getDomain
/// </java-name>
[Dot42.DexImport("getDomain", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetDomain() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the path attribute of the cookie</para><para></para>
/// </summary>
/// <returns>
/// <para>The value of the path attribute. </para>
/// </returns>
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetPath() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Get the Port attribute. It restricts the ports to which a cookie may be returned in a Cookie request header. </para>
/// </summary>
/// <java-name>
/// getPorts
/// </java-name>
[Dot42.DexImport("getPorts", "()[I", AccessFlags = 1025)]
int[] GetPorts() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Indicates whether this cookie requires a secure connection.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if this cookie should only be sent over secure connections, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1025)]
bool IsSecure() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the version of the cookie specification to which this cookie conforms.</para><para></para>
/// </summary>
/// <returns>
/// <para>the version of the cookie. </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns true if this cookie has expired. </para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie has expired. </para>
/// </returns>
/// <java-name>
/// isExpired
/// </java-name>
[Dot42.DexImport("isExpired", "(Ljava/util/Date;)Z", AccessFlags = 1025)]
bool IsExpired(global::Java.Util.Date date) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>CookieOrigin class incapsulates details of an origin server that are relevant when parsing, validating or matching HTTP cookies.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieOrigin
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieOrigin", AccessFlags = 49)]
public sealed partial class CookieOrigin
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "(Ljava/lang/String;ILjava/lang/String;Z)V", AccessFlags = 1)]
public CookieOrigin(string host, int port, string path, bool secure) /* MethodBuilder.Create */
{
}
/// <java-name>
/// getHost
/// </java-name>
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetHost() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPath
/// </java-name>
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
public string GetPath() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getPort
/// </java-name>
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
public int GetPort() /* MethodBuilder.Create */
{
return default(int);
}
/// <java-name>
/// isSecure
/// </java-name>
[Dot42.DexImport("isSecure", "()Z", AccessFlags = 1)]
public bool IsSecure() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// toString
/// </java-name>
[Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)]
public override string ToString() /* MethodBuilder.Create */
{
return default(string);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal CookieOrigin() /* TypeBuilder.AddDefaultConstructor */
{
}
/// <java-name>
/// getHost
/// </java-name>
public string Host
{
[Dot42.DexImport("getHost", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetHost(); }
}
/// <java-name>
/// getPath
/// </java-name>
public string Path
{
[Dot42.DexImport("getPath", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetPath(); }
}
/// <java-name>
/// getPort
/// </java-name>
public int Port
{
[Dot42.DexImport("getPort", "()I", AccessFlags = 1)]
get{ return GetPort(); }
}
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class ISMConstants
/* scope: __dot42__ */
{
/// <java-name>
/// COOKIE
/// </java-name>
[Dot42.DexImport("COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE = "Cookie";
/// <java-name>
/// COOKIE2
/// </java-name>
[Dot42.DexImport("COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string COOKIE2 = "Cookie2";
/// <java-name>
/// SET_COOKIE
/// </java-name>
[Dot42.DexImport("SET_COOKIE", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE = "Set-Cookie";
/// <java-name>
/// SET_COOKIE2
/// </java-name>
[Dot42.DexImport("SET_COOKIE2", "Ljava/lang/String;", AccessFlags = 25)]
public const string SET_COOKIE2 = "Set-Cookie2";
}
/// <summary>
/// <para>Constants and static helpers related to the HTTP state management.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SM
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SM", AccessFlags = 1537)]
public partial interface ISM
/* scope: __dot42__ */
{
}
/// <summary>
/// <para>This cookie comparator ensures that multiple cookies satisfying a common criteria are ordered in the <code>Cookie</code> header such that those with more specific Path attributes precede those with less specific.</para><para>This comparator assumes that Path attributes of two cookies path-match a commmon request-URI. Otherwise, the result of the comparison is undefined. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookiePathComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookiePathComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookiePathComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookiePathComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>This cookie comparator can be used to compare identity of cookies.</para><para>Cookies are considered identical if their names are equal and their domain attributes match ignoring case. </para><para><para> </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieIdentityComparator
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieIdentityComparator", AccessFlags = 33, Signature = "Ljava/lang/Object;Ljava/io/Serializable;Ljava/util/Comparator<Lorg/apache/http/co" +
"okie/Cookie;>;")]
public partial class CookieIdentityComparator : global::Java.Io.ISerializable, global::Java.Util.IComparator<global::Org.Apache.Http.Cookie.ICookie>
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieIdentityComparator() /* MethodBuilder.Create */
{
}
/// <java-name>
/// compare
/// </java-name>
[Dot42.DexImport("compare", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/Cookie;)I", AccessFlags = 1)]
public virtual int Compare(global::Org.Apache.Http.Cookie.ICookie c1, global::Org.Apache.Http.Cookie.ICookie c2) /* MethodBuilder.Create */
{
return default(int);
}
[Dot42.DexImport("java/util/Comparator", "equals", "(Ljava/lang/Object;)Z", AccessFlags = 1025)]
public override bool Equals(object @object) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
}
/// <summary>
/// <para>Cookie specification registry that can be used to obtain the corresponding cookie specification implementation for a given type of type or version of cookie.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpecRegistry
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpecRegistry", AccessFlags = 49)]
public sealed partial class CookieSpecRegistry
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public CookieSpecRegistry() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Registers a CookieSpecFactory with the given identifier. If a specification with the given name already exists it will be overridden. This nameis the same one used to retrieve the CookieSpecFactory from getCookieSpec(String).</para><para><para>#getCookieSpec(String) </para></para>
/// </summary>
/// <java-name>
/// register
/// </java-name>
[Dot42.DexImport("register", "(Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;)V", AccessFlags = 33)]
public void Register(string name, global::Org.Apache.Http.Cookie.ICookieSpecFactory factory) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Unregisters the CookieSpecFactory with the given ID.</para><para></para>
/// </summary>
/// <java-name>
/// unregister
/// </java-name>
[Dot42.DexImport("unregister", "(Ljava/lang/String;)V", AccessFlags = 33)]
public void Unregister(string id) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Gets the cookie specification with the given ID.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;Lorg/apache/http/params/HttpParams;)Lorg/apache/http/cookie/Co" +
"okieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name, global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Gets the cookie specification with the given name.</para><para></para>
/// </summary>
/// <returns>
/// <para>cookie specification</para>
/// </returns>
/// <java-name>
/// getCookieSpec
/// </java-name>
[Dot42.DexImport("getCookieSpec", "(Ljava/lang/String;)Lorg/apache/http/cookie/CookieSpec;", AccessFlags = 33)]
public global::Org.Apache.Http.Cookie.ICookieSpec GetCookieSpec(string name) /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.Cookie.ICookieSpec);
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
public global::Java.Util.IList<string> GetSpecNames() /* MethodBuilder.Create */
{
return default(global::Java.Util.IList<string>);
}
/// <summary>
/// <para>Populates the internal collection of registered cookie specs with the content of the map passed as a parameter.</para><para></para>
/// </summary>
/// <java-name>
/// setItems
/// </java-name>
[Dot42.DexImport("setItems", "(Ljava/util/Map;)V", AccessFlags = 33, Signature = "(Ljava/util/Map<Ljava/lang/String;Lorg/apache/http/cookie/CookieSpecFactory;>;)V")]
public void SetItems(global::Java.Util.IMap<string, global::Org.Apache.Http.Cookie.ICookieSpecFactory> map) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Obtains a list containing names of all registered cookie specs in their default order.</para><para>Note that the DEFAULT policy (if present) is likely to be the same as one of the other policies, but does not have to be.</para><para></para>
/// </summary>
/// <returns>
/// <para>list of registered cookie spec names </para>
/// </returns>
/// <java-name>
/// getSpecNames
/// </java-name>
public global::Java.Util.IList<string> SpecNames
{
[Dot42.DexImport("getSpecNames", "()Ljava/util/List;", AccessFlags = 33, Signature = "()Ljava/util/List<Ljava/lang/String;>;")]
get{ return GetSpecNames(); }
}
}
/// <summary>
/// <para>This interface represents a <code>SetCookie</code> response header sent by the origin server to the HTTP agent in order to maintain a conversational state.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/SetCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/SetCookie", AccessFlags = 1537)]
public partial interface ISetCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// setValue
/// </java-name>
[Dot42.DexImport("setValue", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetValue(string value) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>If a user agent (web browser) presents this cookie to a user, the cookie's purpose will be described using this comment.</para><para><para>getComment() </para></para>
/// </summary>
/// <java-name>
/// setComment
/// </java-name>
[Dot42.DexImport("setComment", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetComment(string comment) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets expiration date. </para><para><b>Note:</b> the object returned by this method is considered immutable. Changing it (e.g. using setTime()) could result in undefined behaviour. Do so at your peril.</para><para><para>Cookie::getExpiryDate </para></para>
/// </summary>
/// <java-name>
/// setExpiryDate
/// </java-name>
[Dot42.DexImport("setExpiryDate", "(Ljava/util/Date;)V", AccessFlags = 1025)]
void SetExpiryDate(global::Java.Util.Date expiryDate) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the domain attribute.</para><para><para>Cookie::getDomain </para></para>
/// </summary>
/// <java-name>
/// setDomain
/// </java-name>
[Dot42.DexImport("setDomain", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetDomain(string domain) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the path attribute.</para><para><para>Cookie::getPath </para></para>
/// </summary>
/// <java-name>
/// setPath
/// </java-name>
[Dot42.DexImport("setPath", "(Ljava/lang/String;)V", AccessFlags = 1025)]
void SetPath(string path) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the secure attribute of the cookie. </para><para>When <code>true</code> the cookie should only be sent using a secure protocol (https). This should only be set when the cookie's originating server used a secure protocol to set the cookie's value.</para><para><para>isSecure() </para></para>
/// </summary>
/// <java-name>
/// setSecure
/// </java-name>
[Dot42.DexImport("setSecure", "(Z)V", AccessFlags = 1025)]
void SetSecure(bool secure) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the version of the cookie specification to which this cookie conforms.</para><para><para>Cookie::getVersion </para></para>
/// </summary>
/// <java-name>
/// setVersion
/// </java-name>
[Dot42.DexImport("setVersion", "(I)V", AccessFlags = 1025)]
void SetVersion(int version) /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Defines the cookie management specification. </para><para>Cookie management specification must define <ul><li><para>rules of parsing "Set-Cookie" header </para></li><li><para>rules of validation of parsed cookies </para></li><li><para>formatting of "Cookie" header </para></li></ul>for a given host, port and path of origin</para><para><para> </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/CookieSpec
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/CookieSpec", AccessFlags = 1537)]
public partial interface ICookieSpec
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns version of the state management this cookie specification conforms to.</para><para></para>
/// </summary>
/// <returns>
/// <para>version of the state management specification </para>
/// </returns>
/// <java-name>
/// getVersion
/// </java-name>
[Dot42.DexImport("getVersion", "()I", AccessFlags = 1025)]
int GetVersion() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Parse the <code>"Set-Cookie"</code> Header into an array of Cookies.</para><para>This method will not perform the validation of the resultant Cookies</para><para><para>validate</para></para>
/// </summary>
/// <returns>
/// <para>an array of <code>Cookie</code>s parsed from the header </para>
/// </returns>
/// <java-name>
/// parse
/// </java-name>
[Dot42.DexImport("parse", "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Lorg/apache/http/Header;Lorg/apache/http/cookie/CookieOrigin;)Ljava/util/List<Lo" +
"rg/apache/http/cookie/Cookie;>;")]
global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> Parse(global::Org.Apache.Http.IHeader header, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Validate the cookie according to validation rules defined by the cookie specification.</para><para></para>
/// </summary>
/// <java-name>
/// validate
/// </java-name>
[Dot42.DexImport("validate", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)V", AccessFlags = 1025)]
void Validate(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Determines if a Cookie matches the target location.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the cookie should be submitted with a request with given attributes, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// match
/// </java-name>
[Dot42.DexImport("match", "(Lorg/apache/http/cookie/Cookie;Lorg/apache/http/cookie/CookieOrigin;)Z", AccessFlags = 1025)]
bool Match(global::Org.Apache.Http.Cookie.ICookie cookie, global::Org.Apache.Http.Cookie.CookieOrigin origin) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Create <code>"Cookie"</code> headers for an array of Cookies.</para><para></para>
/// </summary>
/// <returns>
/// <para>a Header for the given Cookies. </para>
/// </returns>
/// <java-name>
/// formatCookies
/// </java-name>
[Dot42.DexImport("formatCookies", "(Ljava/util/List;)Ljava/util/List;", AccessFlags = 1025, Signature = "(Ljava/util/List<Lorg/apache/http/cookie/Cookie;>;)Ljava/util/List<Lorg/apache/ht" +
"tp/Header;>;")]
global::Java.Util.IList<global::Org.Apache.Http.IHeader> FormatCookies(global::Java.Util.IList<global::Org.Apache.Http.Cookie.ICookie> cookies) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns a request header identifying what version of the state management specification is understood. May be <code>null</code> if the cookie specification does not support <code>Cookie2</code> header. </para>
/// </summary>
/// <java-name>
/// getVersionHeader
/// </java-name>
[Dot42.DexImport("getVersionHeader", "()Lorg/apache/http/Header;", AccessFlags = 1025)]
global::Org.Apache.Http.IHeader GetVersionHeader() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)]
public static partial class IClientCookieConstants
/* scope: __dot42__ */
{
/// <java-name>
/// VERSION_ATTR
/// </java-name>
[Dot42.DexImport("VERSION_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string VERSION_ATTR = "version";
/// <java-name>
/// PATH_ATTR
/// </java-name>
[Dot42.DexImport("PATH_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PATH_ATTR = "path";
/// <java-name>
/// DOMAIN_ATTR
/// </java-name>
[Dot42.DexImport("DOMAIN_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DOMAIN_ATTR = "domain";
/// <java-name>
/// MAX_AGE_ATTR
/// </java-name>
[Dot42.DexImport("MAX_AGE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string MAX_AGE_ATTR = "max-age";
/// <java-name>
/// SECURE_ATTR
/// </java-name>
[Dot42.DexImport("SECURE_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string SECURE_ATTR = "secure";
/// <java-name>
/// COMMENT_ATTR
/// </java-name>
[Dot42.DexImport("COMMENT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENT_ATTR = "comment";
/// <java-name>
/// EXPIRES_ATTR
/// </java-name>
[Dot42.DexImport("EXPIRES_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string EXPIRES_ATTR = "expires";
/// <java-name>
/// PORT_ATTR
/// </java-name>
[Dot42.DexImport("PORT_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string PORT_ATTR = "port";
/// <java-name>
/// COMMENTURL_ATTR
/// </java-name>
[Dot42.DexImport("COMMENTURL_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string COMMENTURL_ATTR = "commenturl";
/// <java-name>
/// DISCARD_ATTR
/// </java-name>
[Dot42.DexImport("DISCARD_ATTR", "Ljava/lang/String;", AccessFlags = 25)]
public const string DISCARD_ATTR = "discard";
}
/// <summary>
/// <para>ClientCookie extends the standard Cookie interface with additional client specific functionality such ability to retrieve original cookie attributes exactly as they were specified by the origin server. This is important for generating the <code>Cookie</code> header because some cookie specifications require that the <code>Cookie</code> header should include certain attributes only if they were specified in the <code>Set-Cookie</code> header.</para><para><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/cookie/ClientCookie
/// </java-name>
[Dot42.DexImport("org/apache/http/cookie/ClientCookie", AccessFlags = 1537)]
public partial interface IClientCookie : global::Org.Apache.Http.Cookie.ICookie
/* scope: __dot42__ */
{
/// <java-name>
/// getAttribute
/// </java-name>
[Dot42.DexImport("getAttribute", "(Ljava/lang/String;)Ljava/lang/String;", AccessFlags = 1025)]
string GetAttribute(string name) /* MethodBuilder.Create */ ;
/// <java-name>
/// containsAttribute
/// </java-name>
[Dot42.DexImport("containsAttribute", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
bool ContainsAttribute(string name) /* MethodBuilder.Create */ ;
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Reactive;
using System.Reactive.Linq;
using System.Security.Cryptography;
using System.Text;
using GitHub.Extensions;
using GitHub.Logging;
using GitHub.Primitives;
using Octokit;
using Octokit.Reactive;
using Serilog;
namespace GitHub.Api
{
public partial class ApiClient : IApiClient
{
const string ProductName = Info.ApplicationInfo.ApplicationDescription;
static readonly ILogger log = LogManager.ForContext<ApiClient>();
readonly IObservableGitHubClient gitHubClient;
string ClientId { get; set; }
string ClientSecret { get; set; }
public ApiClient(HostAddress hostAddress, IObservableGitHubClient gitHubClient)
{
ClientId = ApiClientConfiguration.ClientId;
ClientSecret = ApiClientConfiguration.ClientSecret;
HostAddress = hostAddress;
this.gitHubClient = gitHubClient;
}
partial void Configure();
public IGitHubClient GitHubClient => new GitHubClient(gitHubClient.Connection);
public IObservable<Repository> CreateRepository(NewRepository repository, string login, bool isUser)
{
Guard.ArgumentNotEmptyString(login, nameof(login));
var client = gitHubClient.Repository;
return (isUser ? client.Create(repository) : client.Create(login, repository));
}
public IObservable<Repository> ForkRepository(string owner, string name, NewRepositoryFork repository)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
Guard.ArgumentNotNull(repository, nameof(repository));
var client = gitHubClient.Repository.Forks;
return client.Create(owner, name, repository);
}
public IObservable<PullRequestReview> PostPullRequestReview(
string owner,
string name,
int number,
string commitId,
string body,
PullRequestReviewEvent e)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
var review = new PullRequestReviewCreate
{
Body = body,
CommitId = commitId,
Event = e,
};
return gitHubClient.PullRequest.Review.Create(owner, name, number, review);
}
public IObservable<PullRequestReviewComment> CreatePullRequestReviewComment(
string owner,
string name,
int number,
string body,
string commitId,
string path,
int position)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
Guard.ArgumentNotEmptyString(body, nameof(body));
Guard.ArgumentNotEmptyString(commitId, nameof(commitId));
Guard.ArgumentNotEmptyString(path, nameof(path));
var comment = new PullRequestReviewCommentCreate(body, commitId, path, position);
return gitHubClient.PullRequest.ReviewComment.Create(owner, name, number, comment);
}
public IObservable<PullRequestReviewComment> CreatePullRequestReviewComment(
string owner,
string name,
int number,
string body,
int inReplyTo)
{
var comment = new PullRequestReviewCommentReplyCreate(body, inReplyTo);
return gitHubClient.PullRequest.ReviewComment.CreateReply(owner, name, number, comment);
}
public IObservable<PullRequestReviewComment> EditPullRequestReviewComment(
string owner,
string name,
int number,
string body)
{
var pullRequestReviewCommentEdit = new PullRequestReviewCommentEdit(body);
return gitHubClient.PullRequest.ReviewComment.Edit(owner, name, number, pullRequestReviewCommentEdit);
}
public IObservable<Unit> DeletePullRequestReviewComment(
string owner,
string name,
int number)
{
return gitHubClient.PullRequest.ReviewComment.Delete(owner, name, number);
}
public IObservable<Gist> CreateGist(NewGist newGist)
{
return gitHubClient.Gist.Create(newGist);
}
public IObservable<Repository> GetForks(string owner, string name)
{
return gitHubClient.Repository.Forks.GetAll(owner, name);
}
public IObservable<User> GetUser()
{
return gitHubClient.User.Current();
}
public IObservable<User> GetUser(string login)
{
return gitHubClient.User.Get(login);
}
public IObservable<Organization> GetOrganizations()
{
// Organization.GetAllForCurrent doesn't return all of the information we need (we
// need information about the plan the organization is on in order to enable/disable
// the "Private Repository" checkbox in the "Create Repository" dialog). To get this
// we have to do an Organization.Get on each repository received.
return gitHubClient.Organization
.GetAllForCurrent()
.Select(x => gitHubClient.Organization.Get(x.Login))
.Merge();
}
public IObservable<Repository> GetUserRepositories(RepositoryType repositoryType)
{
var request = new RepositoryRequest
{
Type = repositoryType,
Direction = SortDirection.Ascending,
Sort = RepositorySort.FullName
};
return gitHubClient.Repository.GetAllForCurrent(request);
}
public IObservable<string> GetGitIgnoreTemplates()
{
return gitHubClient.Miscellaneous.GetAllGitIgnoreTemplates();
}
public IObservable<LicenseMetadata> GetLicenses()
{
return gitHubClient.Miscellaneous.GetAllLicenses();
}
public HostAddress HostAddress { get; }
static string GetFingerprint()
{
var fingerprint = ProductName + ":" + GetMachineIdentifier();
return fingerprint.GetSha256Hash();
}
static string GetMachineNameSafe()
{
try
{
return Dns.GetHostName();
}
catch (Exception e)
{
log.Warning(e, "Failed to retrieve host name using `DNS.GetHostName`");
try
{
return Environment.MachineName;
}
catch (Exception ex)
{
log.Warning(ex, "Failed to retrieve host name using `Environment.MachineName`");
return "(unknown)";
}
}
}
static string GetMachineIdentifier()
{
try
{
// adapted from http://stackoverflow.com/a/1561067
var fastedValidNetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
.OrderBy(nic => nic.Speed)
.Where(nic => nic.OperationalStatus == OperationalStatus.Up)
.Select(nic => nic.GetPhysicalAddress().ToString())
.FirstOrDefault(address => address.Length > 12);
return fastedValidNetworkInterface ?? GetMachineNameSafe();
}
catch (Exception e)
{
log.Warning(e, "Could not retrieve MAC address. Fallback to using machine name");
return GetMachineNameSafe();
}
}
public IObservable<Repository> GetRepositoriesForOrganization(string organization)
{
Guard.ArgumentNotEmptyString(organization, nameof(organization));
return gitHubClient.Repository.GetAllForOrg(organization);
}
public IObservable<Unit> DeleteApplicationAuthorization(int id, string twoFactorAuthorizationCode)
{
Guard.ArgumentNotEmptyString(twoFactorAuthorizationCode, nameof(twoFactorAuthorizationCode));
return gitHubClient.Authorization.Delete(id, twoFactorAuthorizationCode);
}
public IObservable<IssueComment> GetIssueComments(string owner, string name, int number)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
return gitHubClient.Issue.Comment.GetAllForIssue(owner, name, number);
}
public IObservable<PullRequest> GetPullRequest(string owner, string name, int number)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
return gitHubClient.PullRequest.Get(owner, name, number);
}
public IObservable<PullRequestFile> GetPullRequestFiles(string owner, string name, int number)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
return gitHubClient.PullRequest.Files(owner, name, number);
}
public IObservable<PullRequestReviewComment> GetPullRequestReviewComments(string owner, string name, int number)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
return gitHubClient.PullRequest.ReviewComment.GetAll(owner, name, number);
}
public IObservable<PullRequest> GetPullRequestsForRepository(string owner, string name)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
return gitHubClient.PullRequest.GetAllForRepository(owner, name,
new PullRequestRequest
{
State = ItemStateFilter.All,
SortProperty = PullRequestSort.Updated,
SortDirection = SortDirection.Descending
});
}
public IObservable<PullRequest> CreatePullRequest(NewPullRequest pullRequest, string owner, string repo)
{
Guard.ArgumentNotNull(pullRequest, nameof(pullRequest));
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(repo, nameof(repo));
return gitHubClient.PullRequest.Create(owner, repo, pullRequest);
}
public IObservable<Repository> GetRepositories()
{
return gitHubClient.Repository.GetAllForCurrent();
}
public IObservable<Branch> GetBranches(string owner, string repo)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(repo, nameof(repo));
return gitHubClient.Repository.Branch.GetAll(owner, repo);
}
public IObservable<Repository> GetRepository(string owner, string repo)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(repo, nameof(repo));
return gitHubClient.Repository.Get(owner, repo);
}
public IObservable<RepositoryContent> GetFileContents(string owner, string name, string reference, string path)
{
Guard.ArgumentNotEmptyString(owner, nameof(owner));
Guard.ArgumentNotEmptyString(name, nameof(name));
Guard.ArgumentNotEmptyString(reference, nameof(reference));
Guard.ArgumentNotEmptyString(path, nameof(path));
return gitHubClient.Repository.Content.GetAllContentsByRef(owner, name, reference, path);
}
}
}
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils.Ntfs
{
using System.IO;
internal delegate File GetFileByIndexFn(long index);
internal delegate File GetFileByRefFn(FileRecordReference reference);
internal delegate Directory GetDirectoryByIndexFn(long index);
internal delegate Directory GetDirectoryByRefFn(FileRecordReference reference);
internal delegate File AllocateFileFn(FileRecordFlags flags);
internal delegate void ForgetFileFn(File file);
internal interface INtfsContext
{
Stream RawStream
{
get;
}
AttributeDefinitions AttributeDefinitions
{
get;
}
UpperCase UpperCase
{
get;
}
BiosParameterBlock BiosParameterBlock
{
get;
}
MasterFileTable Mft
{
get;
}
ClusterBitmap ClusterBitmap
{
get;
}
SecurityDescriptors SecurityDescriptors
{
get;
}
ObjectIds ObjectIds
{
get;
}
ReparsePoints ReparsePoints
{
get;
}
Quotas Quotas
{
get;
}
NtfsOptions Options
{
get;
}
GetFileByIndexFn GetFileByIndex
{
get;
}
GetFileByRefFn GetFileByRef
{
get;
}
GetDirectoryByIndexFn GetDirectoryByIndex
{
get;
}
GetDirectoryByRefFn GetDirectoryByRef
{
get;
}
AllocateFileFn AllocateFile
{
get;
}
ForgetFileFn ForgetFile
{
get;
}
bool ReadOnly
{
get;
}
}
internal sealed class NtfsContext : INtfsContext
{
private Stream _rawStream;
private AttributeDefinitions _attrDefs;
private UpperCase _upperCase;
private BiosParameterBlock _bpb;
private MasterFileTable _mft;
private ClusterBitmap _bitmap;
private SecurityDescriptors _securityDescriptors;
private ObjectIds _objectIds;
private ReparsePoints _reparsePoints;
private Quotas _quotas;
private NtfsOptions _options;
private GetFileByIndexFn _getFileByIndexFn;
private GetFileByRefFn _getFileByRefFn;
private GetDirectoryByIndexFn _getDirByIndexFn;
private GetDirectoryByRefFn _getDirByRefFn;
private AllocateFileFn _allocateFileFn;
private ForgetFileFn _forgetFileFn;
private bool _readOnly;
public Stream RawStream
{
get { return _rawStream; }
set { _rawStream = value; }
}
public AttributeDefinitions AttributeDefinitions
{
get { return _attrDefs; }
set { _attrDefs = value; }
}
public UpperCase UpperCase
{
get { return _upperCase; }
set { _upperCase = value; }
}
public BiosParameterBlock BiosParameterBlock
{
get { return _bpb; }
set { _bpb = value; }
}
public MasterFileTable Mft
{
get { return _mft; }
set { _mft = value; }
}
public ClusterBitmap ClusterBitmap
{
get { return _bitmap; }
set { _bitmap = value; }
}
public SecurityDescriptors SecurityDescriptors
{
get { return _securityDescriptors; }
set { _securityDescriptors = value; }
}
public ObjectIds ObjectIds
{
get { return _objectIds; }
set { _objectIds = value; }
}
public ReparsePoints ReparsePoints
{
get { return _reparsePoints; }
set { _reparsePoints = value; }
}
public Quotas Quotas
{
get { return _quotas; }
set { _quotas = value; }
}
public NtfsOptions Options
{
get { return _options; }
set { _options = value; }
}
public GetFileByIndexFn GetFileByIndex
{
get { return _getFileByIndexFn; }
set { _getFileByIndexFn = value; }
}
public GetFileByRefFn GetFileByRef
{
get { return _getFileByRefFn; }
set { _getFileByRefFn = value; }
}
public GetDirectoryByIndexFn GetDirectoryByIndex
{
get { return _getDirByIndexFn; }
set { _getDirByIndexFn = value; }
}
public GetDirectoryByRefFn GetDirectoryByRef
{
get { return _getDirByRefFn; }
set { _getDirByRefFn = value; }
}
public AllocateFileFn AllocateFile
{
get { return _allocateFileFn; }
set { _allocateFileFn = value; }
}
public ForgetFileFn ForgetFile
{
get { return _forgetFileFn; }
set { _forgetFileFn = value; }
}
public bool ReadOnly
{
get { return _readOnly; }
set { _readOnly = 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
/// <summary>
/// Tests that apply to the filesystem/cache portions of the X509 infrastructure on Unix implementations.
/// </summary>
[Collection("X509Filesystem")]
public static class X509FilesystemTests
{
[Fact]
[OuterLoop]
public static void VerifyCrlCache()
{
string crlDirectory = PersistedFiles.GetUserFeatureDirectory("cryptography", "crls");
string crlFile = Path.Combine(crlDirectory,MicrosoftDotComRootCrlFilename);
Directory.CreateDirectory(crlDirectory);
File.Delete(crlFile);
using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes))
using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
using (var unrelated = new X509Certificate2(TestData.DssCer))
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.ExtraStore.Add(unrelated);
chain.ChainPolicy.ExtraStore.Add(microsoftDotComRoot);
// The very start of the CRL period.
chain.ChainPolicy.VerificationTime = new DateTime(2015, 6, 17, 0, 0, 0, DateTimeKind.Utc);
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly;
chain.ChainPolicy.VerificationFlags |= X509VerificationFlags.AllowUnknownCertificateAuthority;
bool valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Precondition: Chain builds with no revocation checks");
int initialErrorCount = chain.ChainStatus.Length;
Assert.InRange(initialErrorCount, 0, 1);
if (initialErrorCount > 0)
{
Assert.Equal(X509ChainStatusFlags.UntrustedRoot, chain.ChainStatus[0].Status);
}
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
valid = chain.Build(microsoftDotComIssuer);
Assert.False(valid, "Chain should not build validly");
Assert.Equal(initialErrorCount + 1, chain.ChainStatus.Length);
Assert.Equal(X509ChainStatusFlags.RevocationStatusUnknown, chain.ChainStatus[0].Status);
File.WriteAllText(crlFile, MicrosoftDotComRootCrlPem, Encoding.ASCII);
valid = chain.Build(microsoftDotComIssuer);
Assert.True(valid, "Chain should build validly now");
Assert.Equal(initialErrorCount, chain.ChainStatus.Length);
}
}
[Fact]
public static void X509Store_OpenExisting_Fails()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
// Since the directory was explicitly deleted already, this should fail.
Assert.Throws<CryptographicException>(
() => store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly));
});
}
[Fact]
private static void X509Store_AddReadOnly()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
private static void X509Store_AddClosed()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOne()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddOneAfterUpgrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(cert));
// Since we haven't done anything yet, we shouldn't have polluted the hard drive.
Assert.False(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
// Calling Open on an open store changes the access rights:
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(1, storeCerts.Count);
using (X509Certificate2 storeCert = storeCerts[0])
{
Assert.Equal(cert, storeCert);
Assert.NotSame(cert, storeCert);
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DowngradePermissions()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
// Ensure that ReadWrite took effect.
store.Add(certA);
store.Open(OpenFlags.ReadOnly);
// Adding a certificate when the store is ReadOnly should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[Fact]
private static void X509Store_AddAfterDispose()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
// Dispose returns the store to the pre-opened state.
store.Dispose();
// Adding a certificate when the store is closed should fail:
Assert.Throws<CryptographicException>(() => store.Add(certB));
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddAndClear()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Remove(cert);
// The directory should still exist.
Assert.True(Directory.Exists(storeDirectory), "Store Directory Still Exists");
Assert.Equal(0, Directory.GetFiles(storeDirectory).Length);
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddDuplicate()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var cert = new X509Certificate2(TestData.MsCertificate))
using (var certClone = new X509Certificate2(cert.RawData))
{
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
store.Add(certClone);
Assert.Equal(1, Directory.GetFiles(storeDirectory).Length);
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certA, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string[] storeFiles = Directory.GetFiles(storeDirectory);
Assert.Equal(2, storeFiles.Length);
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
storeCert.Dispose();
}
store.Add(certAPrivate);
// It replaces the existing file, the names should be unaffected.
Assert.Equal(storeFiles, Directory.GetFiles(storeDirectory));
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
// The public instance and private instance are .Equal
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_AddTwo_UpgradePrivateKey_NoDowngrade()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certAPrivate = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword))
using (var certAPublic = new X509Certificate2(certAPrivate.RawData))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certAPublic);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
X509Certificate2[] expectedCerts = { certAPublic, certB };
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (before)");
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
// Add the private (checked in X509Store_AddTwo_UpgradePrivateKey)
store.Add(certAPrivate);
// Then add the public again, which shouldn't do anything.
store.Add(certAPublic);
storeCerts = store.Certificates;
Assert.Equal(2, storeCerts.Count);
bool foundCertA = false;
foreach (X509Certificate2 storeCert in storeCerts)
{
if (storeCert.Equals(certAPublic))
{
Assert.True(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (affected cert)");
foundCertA = true;
}
else
{
Assert.False(storeCert.HasPrivateKey, "storeCert.HasPrivateKey (other cert)");
}
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
Assert.True(foundCertA, "foundCertA");
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_DistinctCollections()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(2, Directory.GetFiles(storeDirectory).Length);
X509Certificate2Collection storeCertsA = store.Certificates;
X509Certificate2Collection storeCertsB = store.Certificates;
Assert.NotSame(storeCertsA, storeCertsB);
Assert.Equal(storeCertsA.Count, storeCertsB.Count);
foreach (X509Certificate2 collACert in storeCertsA)
{
int bIndex = storeCertsB.IndexOf(collACert);
Assert.InRange(bIndex, 0, storeCertsB.Count);
X509Certificate2 collBCert = storeCertsB[bIndex];
// Equal is implied by IndexOf working.
Assert.NotSame(collACert, collBCert);
storeCertsB.RemoveAt(bIndex);
collACert.Dispose();
collBCert.Dispose();
}
}
});
}
[Fact]
[OuterLoop(/* Alters user/machine state */)]
private static void X509Store_Add4_Remove1()
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certBClone = new X509Certificate2(certB.RawData))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
store.Add(certC);
store.Add(certD);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
Assert.Equal(4, Directory.GetFiles(storeDirectory).Length);
X509Certificate2[] expectedCerts = { certA, certB, certC, certD };
X509Certificate2Collection storeCerts = store.Certificates;
Assert.Equal(4, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
store.Remove(certBClone);
Assert.Equal(3, Directory.GetFiles(storeDirectory).Length);
expectedCerts = new[] { certA, certC, certD };
storeCerts = store.Certificates;
Assert.Equal(3, storeCerts.Count);
foreach (X509Certificate2 storeCert in storeCerts)
{
Assert.Contains(storeCert, expectedCerts);
storeCert.Dispose();
}
}
});
}
[Theory]
[OuterLoop(/* Alters user/machine state */)]
[InlineData(false)]
[InlineData(true)]
private static void X509Store_MultipleObjects(bool matchCase)
{
RunX509StoreTest(
(store, storeDirectory) =>
{
using (var certA = new X509Certificate2(TestData.MsCertificate))
using (var certB = new X509Certificate2(TestData.DssCer))
using (var certC = new X509Certificate2(TestData.ECDsa256Certificate))
using (var certD = new X509Certificate2(TestData.MicrosoftDotComRootBytes))
{
store.Open(OpenFlags.ReadWrite);
store.Add(certA);
store.Add(certB);
Assert.True(Directory.Exists(storeDirectory), "Directory.Exists(storeDirectory)");
string newName = store.Name;
if (!matchCase)
{
newName = newName.ToUpperInvariant();
Assert.NotEqual(store.Name, newName);
}
using (X509Store storeClone = new X509Store(newName, store.Location))
{
storeClone.Open(OpenFlags.ReadWrite);
X509Certificate2Collection storeCerts = store.Certificates;
X509Certificate2Collection storeCloneCerts = storeClone.Certificates;
Assert.Equal(
storeCerts.OfType<X509Certificate2>(),
storeCloneCerts.OfType<X509Certificate2>());
store.Add(certC);
// The object was added to store, but should show up in both objects
// after re-reading the Certificates property
storeCerts = store.Certificates;
storeCloneCerts = storeClone.Certificates;
Assert.Equal(
storeCerts.OfType<X509Certificate2>(),
storeCloneCerts.OfType<X509Certificate2>());
// Now add one to storeClone to prove bidirectionality.
storeClone.Add(certD);
storeCerts = store.Certificates;
storeCloneCerts = storeClone.Certificates;
Assert.Equal(
storeCerts.OfType<X509Certificate2>(),
storeCloneCerts.OfType<X509Certificate2>());
}
}
});
}
private static void RunX509StoreTest(Action<X509Store, string> testAction)
{
string certStoresFeaturePath = PersistedFiles.GetUserFeatureDirectory("cryptography", "x509stores");
string storeName = "TestStore" + Guid.NewGuid().ToString("N");
string storeDirectory = Path.Combine(certStoresFeaturePath, storeName.ToLowerInvariant());
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
try
{
using (X509Store store = new X509Store(storeName, StoreLocation.CurrentUser))
{
testAction(store, storeDirectory);
}
}
finally
{
try
{
if (Directory.Exists(storeDirectory))
{
Directory.Delete(storeDirectory, true);
}
}
catch
{
// Don't allow any (additional?) I/O errors to propagate.
}
}
}
// `openssl crl -in [MicrosoftDotComRootCrlPem] -noout -hash`.crl
private const string MicrosoftDotComRootCrlFilename = "b204d74a.crl";
// This CRL was downloaded 2015-08-31 20:31 PDT
// It is valid from Jun 17 00:00:00 2015 GMT to Sep 30 23:59:59 2015 GMT
private const string MicrosoftDotComRootCrlPem =
@"-----BEGIN X509 CRL-----
MIICETCB+jANBgkqhkiG9w0BAQUFADCByjELMAkGA1UEBhMCVVMxFzAVBgNVBAoT
DlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBOZXR3b3Jr
MTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2lnbiwgSW5jLiAtIEZvciBhdXRob3Jp
emVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQ
cmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9yaXR5IC0gRzUXDTE1MDYxNzAwMDAw
MFoXDTE1MDkzMDIzNTk1OVowDQYJKoZIhvcNAQEFBQADggEBAFxqobObEqKNSAe+
A9cHCYI7sw+Vc8HuE7E+VZc6ni3a2UHiprYuXDsvD18+cyv/nFSLpLqLmExZrsf/
dzH8GH2HgBTt5aO/nX08EBrDgcjHo9b0VI6ZuOOaEeS0NsRh28Jupfn1Xwcsbdw9
nVh1OaExpHwxgg7pJr4pXzaAjbl3b4QfCPyTd5aaOQOEmqvJtRrMwCna4qQ3p4r6
QYe19/pXqK9my7lSmH1vZ0CmNvQeNPmnx+YmFXYTBgap+Xi2cs6GX/qI04CDzjWi
sm6L0+S1Zx2wMhiYOi0JvrRizf+rIyKkDbPMoYEyXZqcCwSnv6mJQY81vmKRKU5N
WKo2mLw=
-----END X509 CRL-----";
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PowerShell.Commands;
namespace System.Management.Automation
{
/// <summary>
/// Class to manage the caching of analysis data.
/// For performance, module command caching is flattened after discovery. Many modules have nested
/// modules that can only be resolved at runtime - for example,
/// script modules that declare: $env:PATH += "; $psScriptRoot". When
/// doing initial analysis, we include these in 'ExportedCommands'.
/// Changes to these type of modules will not be re-analyzed, unless the user re-imports the module,
/// or runs Get-Module -List.
/// </summary>
internal static class AnalysisCache
{
private static readonly AnalysisCacheData s_cacheData = AnalysisCacheData.Get();
// This dictionary shouldn't see much use, so low concurrency and capacity
private static readonly ConcurrentDictionary<string, string> s_modulesBeingAnalyzed =
new(concurrencyLevel: 1, capacity: 2, StringComparer.OrdinalIgnoreCase);
internal static readonly char[] InvalidCommandNameCharacters = new[]
{
'#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':',
'"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~'
};
internal static ConcurrentDictionary<string, CommandTypes> GetExportedCommands(string modulePath, bool testOnly, ExecutionContext context)
{
bool etwEnabled = CommandDiscoveryEventSource.Log.IsEnabled();
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStart(modulePath);
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath);
return moduleCacheEntry.Commands;
}
ConcurrentDictionary<string, CommandTypes> result = null;
if (!testOnly)
{
var extension = Path.GetExtension(modulePath);
if (extension.Equals(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeManifestModule(modulePath, context, lastWriteTime, etwEnabled);
}
else if (extension.Equals(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeScriptModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeCdxmlModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeDllModule(modulePath, context, lastWriteTime);
}
else if (extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
{
result = AnalyzeDllModule(modulePath, context, lastWriteTime);
}
}
if (result != null)
{
s_cacheData.QueueSerialization();
ModuleIntrinsics.Tracer.WriteLine("Returning {0} exported commands.", result.Count);
}
else
{
ModuleIntrinsics.Tracer.WriteLine("Returning NULL for exported commands.");
}
if (etwEnabled) CommandDiscoveryEventSource.Log.GetModuleExportedCommandsStop(modulePath);
return result;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeManifestModule(string modulePath, ExecutionContext context, DateTime lastWriteTime, bool etwEnabled)
{
ConcurrentDictionary<string, CommandTypes> result = null;
try
{
var moduleManifestProperties = PsUtils.GetModuleManifestProperties(modulePath, PsUtils.FastModuleManifestAnalysisPropertyNames);
if (moduleManifestProperties != null)
{
if (!Configuration.PowerShellConfig.Instance.IsImplicitWinCompatEnabled() && ModuleIsEditionIncompatible(modulePath, moduleManifestProperties))
{
ModuleIntrinsics.Tracer.WriteLine($"Module lies on the Windows System32 legacy module path and is incompatible with current PowerShell edition, skipping module: {modulePath}");
return null;
}
Version version;
if (ModuleUtils.IsModuleInVersionSubdirectory(modulePath, out version))
{
var versionInManifest = LanguagePrimitives.ConvertTo<Version>(moduleManifestProperties["ModuleVersion"]);
if (version != versionInManifest)
{
ModuleIntrinsics.Tracer.WriteLine("ModuleVersion in manifest does not match versioned module directory, skipping module: {0}", modulePath);
return null;
}
}
result = new ConcurrentDictionary<string, CommandTypes>(3, moduleManifestProperties.Count, StringComparer.OrdinalIgnoreCase);
var sawWildcard = false;
var hadCmdlets = AddPsd1EntryToResult(result, moduleManifestProperties["CmdletsToExport"], CommandTypes.Cmdlet, ref sawWildcard);
var hadFunctions = AddPsd1EntryToResult(result, moduleManifestProperties["FunctionsToExport"], CommandTypes.Function, ref sawWildcard);
var hadAliases = AddPsd1EntryToResult(result, moduleManifestProperties["AliasesToExport"], CommandTypes.Alias, ref sawWildcard);
var analysisSucceeded = hadCmdlets && hadFunctions && hadAliases;
if (!analysisSucceeded && !sawWildcard && (hadCmdlets || hadFunctions))
{
// If we're missing CmdletsToExport, that might still be OK, but only if we have a script module.
// Likewise, if we're missing FunctionsToExport, that might be OK, but only if we have a binary module.
analysisSucceeded = !CheckModulesTypesInManifestAgainstExportedCommands(moduleManifestProperties, hadCmdlets, hadFunctions, hadAliases);
}
if (analysisSucceeded)
{
var moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = modulePath,
LastWriteTime = lastWriteTime,
Commands = result,
TypesAnalyzed = false,
Types = new ConcurrentDictionary<string, TypeAttributes>(1, 8, StringComparer.OrdinalIgnoreCase)
};
s_cacheData.Entries[modulePath] = moduleCacheEntry;
}
else
{
result = null;
}
}
}
catch (Exception e)
{
if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisException(modulePath, e.Message);
// Ignore the errors, proceed with the usual module analysis
ModuleIntrinsics.Tracer.WriteLine("Exception on fast-path analysis of module {0}", modulePath);
}
if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleManifestAnalysisResult(modulePath, result != null);
return result ?? AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
/// <summary>
/// Check if a module is compatible with the current PSEdition given its path and its manifest properties.
/// </summary>
/// <param name="modulePath">The path to the module.</param>
/// <param name="moduleManifestProperties">The properties of the module's manifest.</param>
/// <returns></returns>
internal static bool ModuleIsEditionIncompatible(string modulePath, Hashtable moduleManifestProperties)
{
#if UNIX
return false;
#else
if (!ModuleUtils.IsOnSystem32ModulePath(modulePath))
{
return false;
}
if (!moduleManifestProperties.ContainsKey("CompatiblePSEditions"))
{
return true;
}
return !Utils.IsPSEditionSupported(LanguagePrimitives.ConvertTo<string[]>(moduleManifestProperties["CompatiblePSEditions"]));
#endif
}
internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bool hadCmdlets, bool hadFunctions, bool hadAliases)
{
if (!(modulePathObj is string modulePath))
return true;
if (modulePath.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase))
{
// A script module can't exactly define cmdlets, but it can import a binary module (as nested), so
// it can indirectly define cmdlets. And obviously a script module can define functions and aliases.
// If we got here, one of those is missing, so analysis is required.
return true;
}
if (modulePath.EndsWith(StringLiterals.PowerShellCmdletizationFileExtension, StringComparison.OrdinalIgnoreCase))
{
// A cdxml module can only define functions and aliases, so if we have both, no more analysis is required.
return !hadFunctions || !hadAliases;
}
if (modulePath.EndsWith(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase))
{
// A dll just exports cmdlets, so if the manifest doesn't explicitly export any cmdlets,
// more analysis is required. If the module exports aliases, we can't discover that analyzing
// the binary, so aliases are always required to be explicit (no wildcards) in the manifest.
return !hadCmdlets;
}
if (modulePath.EndsWith(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))
{
// A dll just exports cmdlets, so if the manifest doesn't explicitly export any cmdlets,
// more analysis is required. If the module exports aliases, we can't discover that analyzing
// the binary, so aliases are always required to be explicit (no wildcards) in the manifest.
return !hadCmdlets;
}
// Any other extension (or no extension), just assume the worst and analyze the module
return true;
}
// Returns true if we need to analyze the manifest module in Get-Module because
// our quick and dirty module manifest analysis is missing something not easily
// discovered.
//
// TODO - psm1 modules are actually easily handled, so if we only saw a psm1 here,
// we should just analyze it and not fall back on Get-Module -List.
private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable moduleManifestProperties, bool hadCmdlets, bool hadFunctions, bool hadAliases)
{
var rootModule = moduleManifestProperties["RootModule"];
if (rootModule != null && ModuleAnalysisViaGetModuleRequired(rootModule, hadCmdlets, hadFunctions, hadAliases))
return true;
var moduleToProcess = moduleManifestProperties["ModuleToProcess"];
if (moduleToProcess != null && ModuleAnalysisViaGetModuleRequired(moduleToProcess, hadCmdlets, hadFunctions, hadAliases))
return true;
var nestedModules = moduleManifestProperties["NestedModules"];
if (nestedModules != null)
{
var nestedModule = nestedModules as string;
if (nestedModule != null)
{
return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases);
}
if (!(nestedModules is object[] nestedModuleArray))
return true;
foreach (var element in nestedModuleArray)
{
if (ModuleAnalysisViaGetModuleRequired(element, hadCmdlets, hadFunctions, hadAliases))
return true;
}
}
return false;
}
private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, string command, CommandTypes commandTypeToAdd, ref bool sawWildcard)
{
if (WildcardPattern.ContainsWildcardCharacters(command))
{
sawWildcard = true;
return false;
}
// An empty string is one way of saying "no exported commands".
if (command.Length != 0)
{
CommandTypes commandTypes;
if (result.TryGetValue(command, out commandTypes))
{
commandTypes |= commandTypeToAdd;
}
else
{
commandTypes = commandTypeToAdd;
}
result[command] = commandTypes;
}
return true;
}
private static bool AddPsd1EntryToResult(ConcurrentDictionary<string, CommandTypes> result, object value, CommandTypes commandTypeToAdd, ref bool sawWildcard)
{
string command = value as string;
if (command != null)
{
return AddPsd1EntryToResult(result, command, commandTypeToAdd, ref sawWildcard);
}
object[] commands = value as object[];
if (commands != null)
{
foreach (var o in commands)
{
if (!AddPsd1EntryToResult(result, o, commandTypeToAdd, ref sawWildcard))
return false;
}
// An empty array is still success, that's how a manifest declares that
// no entries are exported (unlike the lack of an entry, or $null).
return true;
}
// Unknown type, let Get-Module -List deal with this manifest
return false;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeScriptModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
var scriptAnalysis = ScriptAnalysis.Analyze(modulePath, context);
if (scriptAnalysis == null)
{
return null;
}
List<WildcardPattern> scriptAnalysisPatterns = new List<WildcardPattern>();
foreach (string discoveredCommandFilter in scriptAnalysis.DiscoveredCommandFilters)
{
scriptAnalysisPatterns.Add(new WildcardPattern(discoveredCommandFilter));
}
var result = new ConcurrentDictionary<string, CommandTypes>(3,
scriptAnalysis.DiscoveredExports.Count + scriptAnalysis.DiscoveredAliases.Count,
StringComparer.OrdinalIgnoreCase);
// Add any directly discovered exports
foreach (var command in scriptAnalysis.DiscoveredExports)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true))
{
if (command.IndexOfAny(InvalidCommandNameCharacters) < 0)
{
result[command] = CommandTypes.Function;
}
}
}
// Add the discovered aliases
foreach (var pair in scriptAnalysis.DiscoveredAliases)
{
var commandName = pair.Key;
// These are already filtered
if (commandName.IndexOfAny(InvalidCommandNameCharacters) < 0)
{
result.AddOrUpdate(commandName, CommandTypes.Alias,
static (_, existingCommandType) => existingCommandType | CommandTypes.Alias);
}
}
// Add any files in PsScriptRoot if it added itself to the path
if (scriptAnalysis.AddsSelfToPath)
{
string baseDirectory = Path.GetDirectoryName(modulePath);
try
{
foreach (string item in Directory.EnumerateFiles(baseDirectory, "*.ps1"))
{
var command = Path.GetFileNameWithoutExtension(item);
result.AddOrUpdate(command, CommandTypes.ExternalScript,
static (_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript);
}
}
catch (UnauthorizedAccessException)
{
// Consume this exception here
}
}
ConcurrentDictionary<string, TypeAttributes> exportedClasses = new(
concurrencyLevel: 1,
capacity: scriptAnalysis.DiscoveredClasses.Count,
StringComparer.OrdinalIgnoreCase);
foreach (var exportedClass in scriptAnalysis.DiscoveredClasses)
{
exportedClasses[exportedClass.Name] = exportedClass.TypeAttributes;
}
var moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = modulePath,
LastWriteTime = lastWriteTime,
Commands = result,
TypesAnalyzed = true,
Types = exportedClasses
};
s_cacheData.Entries[modulePath] = moduleCacheEntry;
return result;
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeCdxmlModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
return AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeDllModule(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
return AnalyzeTheOldWay(modulePath, context, lastWriteTime);
}
private static ConcurrentDictionary<string, CommandTypes> AnalyzeTheOldWay(string modulePath, ExecutionContext context, DateTime lastWriteTime)
{
try
{
// If we're already analyzing this module, let the recursion bottom out.
if (!s_modulesBeingAnalyzed.TryAdd(modulePath, modulePath))
{
ModuleIntrinsics.Tracer.WriteLine("{0} is already being analyzed. Exiting.", modulePath);
return null;
}
// Record that we're analyzing this specific module so that we don't get stuck in recursion
ModuleIntrinsics.Tracer.WriteLine("Started analysis: {0}", modulePath);
CallGetModuleDashList(context, modulePath);
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
return moduleCacheEntry.Commands;
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
}
finally
{
ModuleIntrinsics.Tracer.WriteLine("Finished analysis: {0}", modulePath);
s_modulesBeingAnalyzed.TryRemove(modulePath, out modulePath);
}
return null;
}
/// <summary>
/// Return the exported types for a specific module.
/// If the module is already cache, return from cache, else cache the module.
/// Also re-cache the module if the cached item is stale.
/// </summary>
/// <param name="modulePath">Path to the module to get exported types from.</param>
/// <param name="context">Current Context.</param>
/// <returns></returns>
internal static ConcurrentDictionary<string, TypeAttributes> GetExportedClasses(string modulePath, ExecutionContext context)
{
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry) && moduleCacheEntry.TypesAnalyzed)
{
return moduleCacheEntry.Types;
}
try
{
CallGetModuleDashList(context, modulePath);
if (GetModuleEntryFromCache(modulePath, out lastWriteTime, out moduleCacheEntry))
{
return moduleCacheEntry.Types;
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
}
return null;
}
internal static void CacheModuleExports(PSModuleInfo module, ExecutionContext context)
{
ModuleIntrinsics.Tracer.WriteLine("Requested caching for {0}", module.Name);
// Don't cache incompatible modules on the system32 module path even if loaded with
// -SkipEditionCheck, since it will break subsequent sessions
if (!Configuration.PowerShellConfig.Instance.IsImplicitWinCompatEnabled() && !module.IsConsideredEditionCompatible)
{
ModuleIntrinsics.Tracer.WriteLine($"Module '{module.Name}' not edition compatible and not cached.");
return;
}
DateTime lastWriteTime;
ModuleCacheEntry moduleCacheEntry;
GetModuleEntryFromCache(module.Path, out lastWriteTime, out moduleCacheEntry);
var realExportedCommands = module.ExportedCommands;
var realExportedClasses = module.GetExportedTypeDefinitions();
ConcurrentDictionary<string, CommandTypes> exportedCommands;
ConcurrentDictionary<string, TypeAttributes> exportedClasses;
// First see if the existing module info is sufficient. GetModuleEntryFromCache does LastWriteTime
// verification, so this will also return nothing if the cache is out of date or corrupt.
if (moduleCacheEntry != null)
{
bool needToUpdate = false;
// We need to iterate and check as exportedCommands will have more item as it can have aliases as well.
exportedCommands = moduleCacheEntry.Commands;
foreach (var pair in realExportedCommands)
{
var commandName = pair.Key;
var realCommandType = pair.Value.CommandType;
CommandTypes commandType;
if (!exportedCommands.TryGetValue(commandName, out commandType) || commandType != realCommandType)
{
needToUpdate = true;
break;
}
}
exportedClasses = moduleCacheEntry.Types;
foreach (var pair in realExportedClasses)
{
var className = pair.Key;
var realTypeAttributes = pair.Value.TypeAttributes;
TypeAttributes typeAttributes;
if (!exportedClasses.TryGetValue(className, out typeAttributes) ||
typeAttributes != realTypeAttributes)
{
needToUpdate = true;
break;
}
}
// Update or not, we've analyzed commands and types now.
moduleCacheEntry.TypesAnalyzed = true;
if (!needToUpdate)
{
ModuleIntrinsics.Tracer.WriteLine("Existing cached info up-to-date. Skipping.");
return;
}
exportedCommands.Clear();
exportedClasses.Clear();
}
else
{
exportedCommands = new ConcurrentDictionary<string, CommandTypes>(3, realExportedCommands.Count, StringComparer.OrdinalIgnoreCase);
exportedClasses = new ConcurrentDictionary<string, TypeAttributes>(1, realExportedClasses.Count, StringComparer.OrdinalIgnoreCase);
moduleCacheEntry = new ModuleCacheEntry
{
ModulePath = module.Path,
LastWriteTime = lastWriteTime,
Commands = exportedCommands,
TypesAnalyzed = true,
Types = exportedClasses
};
moduleCacheEntry = s_cacheData.Entries.GetOrAdd(module.Path, moduleCacheEntry);
}
// We need to update the cache
foreach (var exportedCommand in realExportedCommands.Values)
{
ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", exportedCommand.Name);
exportedCommands.GetOrAdd(exportedCommand.Name, exportedCommand.CommandType);
}
foreach (var pair in realExportedClasses)
{
var className = pair.Key;
ModuleIntrinsics.Tracer.WriteLine("Caching command: {0}", className);
moduleCacheEntry.Types.AddOrUpdate(className, pair.Value.TypeAttributes, (k, t) => t);
}
s_cacheData.QueueSerialization();
}
private static void CallGetModuleDashList(ExecutionContext context, string modulePath)
{
CommandInfo commandInfo = new CmdletInfo("Get-Module", typeof(GetModuleCommand), null, null, context);
Command getModuleCommand = new Command(commandInfo);
try
{
PowerShell.Create(RunspaceMode.CurrentRunspace)
.AddCommand(getModuleCommand)
.AddParameter("List", true)
.AddParameter("ErrorAction", ActionPreference.Ignore)
.AddParameter("WarningAction", ActionPreference.Ignore)
.AddParameter("InformationAction", ActionPreference.Ignore)
.AddParameter("Verbose", false)
.AddParameter("Debug", false)
.AddParameter("Name", modulePath)
.Invoke();
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Module analysis generated an exception: {0}", e);
// Catch-all OK, third-party call-out.
}
}
private static bool GetModuleEntryFromCache(string modulePath, out DateTime lastWriteTime, out ModuleCacheEntry moduleCacheEntry)
{
try
{
lastWriteTime = new FileInfo(modulePath).LastWriteTime;
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking LastWriteTime on module {0}: {1}", modulePath, e.Message);
lastWriteTime = DateTime.MinValue;
}
if (s_cacheData.Entries.TryGetValue(modulePath, out moduleCacheEntry))
{
if (lastWriteTime == moduleCacheEntry.LastWriteTime)
{
return true;
}
ModuleIntrinsics.Tracer.WriteLine("{0}: cache entry out of date, cached on {1}, last updated on {2}",
modulePath, moduleCacheEntry.LastWriteTime, lastWriteTime);
s_cacheData.Entries.TryRemove(modulePath, out moduleCacheEntry);
}
moduleCacheEntry = null;
return false;
}
}
internal sealed class AnalysisCacheData
{
private static byte[] GetHeader()
{
return new byte[]
{
0x50, 0x53, 0x4d, 0x4f, 0x44, 0x55, 0x4c, 0x45, 0x43, 0x41, 0x43, 0x48, 0x45, // PSMODULECACHE
0x01 // version #
};
}
// The last time the index was maintained.
public DateTime LastReadTime { get; set; }
public ConcurrentDictionary<string, ModuleCacheEntry> Entries { get; set; }
private int _saveCacheToDiskQueued;
private bool _saveCacheToDisk = true;
public void QueueSerialization()
{
// We expect many modules to rapidly call for serialization.
// Instead of doing it right away, we'll queue a task that starts writing
// after it seems like we've stopped adding stuff to write out. This is
// avoids blocking the pipeline thread waiting for the write to finish.
// We want to make sure we only queue one task.
if (_saveCacheToDisk && Interlocked.Increment(ref _saveCacheToDiskQueued) == 1)
{
Task.Run(async delegate
{
// Wait a while before assuming we've finished the updates,
// writing the cache out in a timely matter isn't too important
// now anyway.
await Task.Delay(10000).ConfigureAwait(false);
int counter1, counter2;
do
{
// Check the counter a couple times with a delay,
// if it's stable, then proceed with writing.
counter1 = _saveCacheToDiskQueued;
await Task.Delay(3000).ConfigureAwait(false);
counter2 = _saveCacheToDiskQueued;
} while (counter1 != counter2);
Serialize(s_cacheStoreLocation);
});
}
}
// Remove entries that are not needed anymore, e.g. if a module was removed.
// If anything is removed, save the cache.
private void Cleanup()
{
Diagnostics.Assert(Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null,
"Caller to check environment variable before calling");
bool removedSomething = false;
var keys = Entries.Keys;
foreach (var key in keys)
{
if (!File.Exists(key))
{
removedSomething |= Entries.TryRemove(key, out ModuleCacheEntry _);
}
}
if (removedSomething)
{
QueueSerialization();
}
}
private static unsafe void Write(int val, byte[] bytes, FileStream stream)
{
Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array");
fixed (byte* b = bytes) *((int*)b) = val;
stream.Write(bytes, 0, 4);
}
private static unsafe void Write(long val, byte[] bytes, FileStream stream)
{
Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array");
fixed (byte* b = bytes) *((long*)b) = val;
stream.Write(bytes, 0, 8);
}
private static void Write(string val, byte[] bytes, FileStream stream)
{
Write(val.Length, bytes, stream);
bytes = Encoding.UTF8.GetBytes(val);
stream.Write(bytes, 0, bytes.Length);
}
private void Serialize(string filename)
{
AnalysisCacheData fromOtherProcess = null;
Diagnostics.Assert(_saveCacheToDisk, "Serialize should never be called without going through QueueSerialization which has a check");
try
{
if (File.Exists(filename))
{
var fileLastWriteTime = new FileInfo(filename).LastWriteTime;
if (fileLastWriteTime > this.LastReadTime)
{
fromOtherProcess = Deserialize(filename);
}
}
else
{
// Make sure the folder exists
var folder = Path.GetDirectoryName(filename);
if (!Directory.Exists(folder))
{
try
{
Directory.CreateDirectory(folder);
}
catch (UnauthorizedAccessException)
{
// service accounts won't be able to create directory
_saveCacheToDisk = false;
return;
}
}
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache {0}: {1} ", filename, e.Message);
}
if (fromOtherProcess != null)
{
// We should merge with what another process wrote so we don't clobber useful analysis
foreach (var otherEntryPair in fromOtherProcess.Entries)
{
var otherModuleName = otherEntryPair.Key;
var otherEntry = otherEntryPair.Value;
ModuleCacheEntry thisEntry;
if (Entries.TryGetValue(otherModuleName, out thisEntry))
{
if (otherEntry.LastWriteTime > thisEntry.LastWriteTime)
{
// The other entry is newer, take it over ours
Entries[otherModuleName] = otherEntry;
}
}
else
{
Entries[otherModuleName] = otherEntry;
}
}
}
// "PSMODULECACHE" -> 13 bytes
// byte ( 1 byte) -> version
// int ( 4 bytes) -> count of entries
// entries (?? bytes) -> all entries
//
// each entry is
// DateTime ( 8 bytes) -> last write time for module file
// int ( 4 bytes) -> path length
// string (?? bytes) -> utf8 encoded path
// int ( 4 bytes) -> count of commands
// commands (?? bytes) -> all commands
// int ( 4 bytes) -> count of types, -1 means unanalyzed (and 0 items serialized)
// types (?? bytes) -> all types
//
// each command is
// int ( 4 bytes) -> command name length
// string (?? bytes) -> utf8 encoded command name
// int ( 4 bytes) -> CommandTypes enum
//
// each type is
// int ( 4 bytes) -> type name length
// string (?? bytes) -> utf8 encoded type name
// int ( 4 bytes) -> type attributes
try
{
var bytes = new byte[8];
using (var stream = File.Create(filename))
{
var headerBytes = GetHeader();
stream.Write(headerBytes, 0, headerBytes.Length);
// Count of entries
Write(Entries.Count, bytes, stream);
foreach (var pair in Entries.ToArray())
{
var path = pair.Key;
var entry = pair.Value;
// Module last write time
Write(entry.LastWriteTime.Ticks, bytes, stream);
// Module path
Write(path, bytes, stream);
// Commands
var commandPairs = entry.Commands.ToArray();
Write(commandPairs.Length, bytes, stream);
foreach (var command in commandPairs)
{
Write(command.Key, bytes, stream);
Write((int)command.Value, bytes, stream);
}
// Types
var typePairs = entry.Types.ToArray();
Write(entry.TypesAnalyzed ? typePairs.Length : -1, bytes, stream);
foreach (var type in typePairs)
{
Write(type.Key, bytes, stream);
Write((int)type.Value, bytes, stream);
}
}
}
// We just wrote the file, note this so we can detect writes from another process
LastReadTime = new FileInfo(filename).LastWriteTime;
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception writing module analysis cache {0}: {1} ", filename, e.Message);
}
// Reset our counter so we can write again if asked.
Interlocked.Exchange(ref _saveCacheToDiskQueued, 0);
}
private const string TruncatedErrorMessage = "module cache file appears truncated";
private const string InvalidSignatureErrorMessage = "module cache signature not valid";
private const string PossibleCorruptionErrorMessage = "possible corruption in module cache";
private static unsafe long ReadLong(FileStream stream, byte[] bytes)
{
Diagnostics.Assert(bytes.Length >= 8, "Must pass a large enough byte array");
if (stream.Read(bytes, 0, 8) != 8)
throw new Exception(TruncatedErrorMessage);
fixed (byte* b = bytes)
return *(long*)b;
}
private static unsafe int ReadInt(FileStream stream, byte[] bytes)
{
Diagnostics.Assert(bytes.Length >= 4, "Must pass a large enough byte array");
if (stream.Read(bytes, 0, 4) != 4)
throw new Exception(TruncatedErrorMessage);
fixed (byte* b = bytes)
return *(int*)b;
}
private static string ReadString(FileStream stream, ref byte[] bytes)
{
int length = ReadInt(stream, bytes);
if (length > 10 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
if (length > bytes.Length)
bytes = new byte[length];
if (stream.Read(bytes, 0, length) != length)
throw new Exception(TruncatedErrorMessage);
return Encoding.UTF8.GetString(bytes, 0, length);
}
private static void ReadHeader(FileStream stream, byte[] bytes)
{
var headerBytes = GetHeader();
var length = headerBytes.Length;
Diagnostics.Assert(bytes.Length >= length, "must pass a large enough byte array");
if (stream.Read(bytes, 0, length) != length)
throw new Exception(TruncatedErrorMessage);
for (int i = 0; i < length; i++)
{
if (bytes[i] != headerBytes[i])
{
throw new Exception(InvalidSignatureErrorMessage);
}
}
// No need to return - we don't use it other than to detect the correct file format
}
public static AnalysisCacheData Deserialize(string filename)
{
using (var stream = File.OpenRead(filename))
{
var result = new AnalysisCacheData { LastReadTime = DateTime.Now };
var bytes = new byte[1024];
// Header
// "PSMODULECACHE" -> 13 bytes
// byte ( 1 byte) -> version
ReadHeader(stream, bytes);
// int ( 4 bytes) -> count of entries
int entries = ReadInt(stream, bytes);
if (entries > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
result.Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, entries, StringComparer.OrdinalIgnoreCase);
// entries (?? bytes) -> all entries
while (entries > 0)
{
// DateTime ( 8 bytes) -> last write time for module file
var lastWriteTime = new DateTime(ReadLong(stream, bytes));
// int ( 4 bytes) -> path length
// string (?? bytes) -> utf8 encoded path
var path = ReadString(stream, ref bytes);
// int ( 4 bytes) -> count of commands
var countItems = ReadInt(stream, bytes);
if (countItems > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
var commands = new ConcurrentDictionary<string, CommandTypes>(/*concurrency*/3, countItems, StringComparer.OrdinalIgnoreCase);
// commands (?? bytes) -> all commands
while (countItems > 0)
{
// int ( 4 bytes) -> command name length
// string (?? bytes) -> utf8 encoded command name
var commandName = ReadString(stream, ref bytes);
// int ( 4 bytes) -> CommandTypes enum
var commandTypes = (CommandTypes)ReadInt(stream, bytes);
// Ignore empty entries (possible corruption in the cache or bug?)
if (!string.IsNullOrWhiteSpace(commandName))
commands[commandName] = commandTypes;
countItems -= 1;
}
// int ( 4 bytes) -> count of types
countItems = ReadInt(stream, bytes);
bool typesAnalyzed = countItems != -1;
if (!typesAnalyzed)
countItems = 0;
if (countItems > 20 * 1024)
throw new Exception(PossibleCorruptionErrorMessage);
var types = new ConcurrentDictionary<string, TypeAttributes>(1, countItems, StringComparer.OrdinalIgnoreCase);
// types (?? bytes) -> all types
while (countItems > 0)
{
// int ( 4 bytes) -> type name length
// string (?? bytes) -> utf8 encoded type name
var typeName = ReadString(stream, ref bytes);
// int ( 4 bytes) -> type attributes
var typeAttributes = (TypeAttributes)ReadInt(stream, bytes);
// Ignore empty entries (possible corruption in the cache or bug?)
if (!string.IsNullOrWhiteSpace(typeName))
types[typeName] = typeAttributes;
countItems -= 1;
}
var entry = new ModuleCacheEntry
{
ModulePath = path,
LastWriteTime = lastWriteTime,
Commands = commands,
TypesAnalyzed = typesAnalyzed,
Types = types
};
result.Entries[path] = entry;
entries -= 1;
}
if (Environment.GetEnvironmentVariable("PSDisableModuleAnalysisCacheCleanup") == null)
{
Task.Delay(10000).ContinueWith(_ => result.Cleanup());
}
return result;
}
}
internal static AnalysisCacheData Get()
{
int retryCount = 3;
do
{
try
{
if (File.Exists(s_cacheStoreLocation))
{
return Deserialize(s_cacheStoreLocation);
}
}
catch (Exception e)
{
ModuleIntrinsics.Tracer.WriteLine("Exception checking module analysis cache: " + e.Message);
if ((object)e.Message == (object)TruncatedErrorMessage
|| (object)e.Message == (object)InvalidSignatureErrorMessage
|| (object)e.Message == (object)PossibleCorruptionErrorMessage)
{
// Don't retry if we detected something is wrong with the file
// (as opposed to the file being locked or something else)
break;
}
}
retryCount -= 1;
Thread.Sleep(25); // Sleep a bit to give time for another process to finish writing the cache
} while (retryCount > 0);
return new AnalysisCacheData
{
LastReadTime = DateTime.Now,
// Capacity set to 100 - a bit bigger than the # of modules on a default Win10 client machine
// Concurrency=3 to not create too many locks, contention is unclear, but the old code had a single lock
Entries = new ConcurrentDictionary<string, ModuleCacheEntry>(/*concurrency*/3, /*capacity*/100, StringComparer.OrdinalIgnoreCase)
};
}
private AnalysisCacheData()
{
}
private static readonly string s_cacheStoreLocation;
static AnalysisCacheData()
{
// If user defines a custom cache path, then use that.
string userDefinedCachePath = Environment.GetEnvironmentVariable("PSModuleAnalysisCachePath");
if (!string.IsNullOrEmpty(userDefinedCachePath))
{
s_cacheStoreLocation = userDefinedCachePath;
return;
}
string cacheFileName = "ModuleAnalysisCache";
// When multiple copies of pwsh are on the system, they should use their own copy of the cache.
// Append hash of `$PSHOME` to cacheFileName.
string hashString = CRC32Hash.ComputeHash(Utils.DefaultPowerShellAppBase);
cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString);
if (ExperimentalFeature.EnabledExperimentalFeatureNames.Count > 0)
{
// If any experimental features are enabled, we cannot use the default cache file because those
// features may expose commands that are not available in a regular powershell session, and we
// should not cache those commands in the default cache file because that will result in wrong
// auto-completion suggestions when the default cache file is used in another powershell session.
//
// Here we will generate a cache file name that represent the combination of enabled feature names.
// We first convert enabled feature names to lower case, then we sort the feature names, and then
// compute an CRC32 hash from the sorted feature names. We will use the CRC32 hash to generate the
// cache file name.
int index = 0;
string[] featureNames = new string[ExperimentalFeature.EnabledExperimentalFeatureNames.Count];
foreach (string featureName in ExperimentalFeature.EnabledExperimentalFeatureNames)
{
featureNames[index++] = featureName.ToLowerInvariant();
}
Array.Sort(featureNames);
string allNames = string.Join(Environment.NewLine, featureNames);
// Use CRC32 because it's faster.
// It's very unlikely to get collision from hashing the combinations of enabled features names.
hashString = CRC32Hash.ComputeHash(allNames);
cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString);
}
s_cacheStoreLocation = Path.Combine(Platform.CacheDirectory, cacheFileName);
}
}
[DebuggerDisplay("ModulePath = {ModulePath}")]
internal class ModuleCacheEntry
{
public DateTime LastWriteTime;
public string ModulePath;
public bool TypesAnalyzed;
public ConcurrentDictionary<string, CommandTypes> Commands;
public ConcurrentDictionary<string, TypeAttributes> Types;
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure.Commands.Common;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.WindowsAzure.Commands.Utilities.Properties;
using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Common;
using Microsoft.WindowsAzure.Commands.Utilities.Scheduler.Model;
using Microsoft.WindowsAzure.Management.Scheduler;
using Microsoft.WindowsAzure.Management.Scheduler.Models;
using Microsoft.WindowsAzure.Scheduler;
using Microsoft.WindowsAzure.Scheduler.Models;
using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
namespace Microsoft.WindowsAzure.Commands.Utilities.Scheduler
{
public partial class SchedulerMgmntClient
{
private SchedulerManagementClient schedulerManagementClient;
private CloudServiceManagementClient csmClient;
private IAzureSubscription currentSubscription;
private const string SupportedRegionsKey = "SupportedGeoRegions";
private const string FreeMaxJobCountKey = "PlanDetail:Free:Quota:MaxJobCount";
private const string FreeMinRecurrenceKey = "PlanDetail:Free:Quota:MinRecurrence";
private const string StandardMaxJobCountKey = "PlanDetail:Standard:Quota:MaxJobCount";
private const string StandardMinRecurrenceKey = "PlanDetail:Standard:Quota:MinRecurrence";
private const string PremiumMaxJobCountKey = "PlanDetail:Premium:Quota:MaxJobCount";
private const string PremiumMinRecurrenceKey = "PlanDetail:Premium:Quota:MinRecurrence";
private int FreeMaxJobCountValue { get; set; }
private TimeSpan FreeMinRecurrenceValue { get; set; }
private int StandardMaxJobCountValue { get; set; }
private TimeSpan StandardMinRecurrenceValue { get; set; }
private int PremiumMaxJobCountValue { get; set; }
private TimeSpan PremiumMinRecurrenceValue { get; set; }
private List<string> AvailableRegions { get; set; }
/// <summary>
/// Creates new Scheduler Management Convenience Client
/// </summary>
/// <param name="subscription">Subscription containing websites to manipulate</param>
public SchedulerMgmntClient(AzureSMProfile profile, IAzureSubscription subscription)
{
currentSubscription = subscription;
csmClient = AzureSession.Instance.ClientFactory.CreateClient<CloudServiceManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
schedulerManagementClient = AzureSession.Instance.ClientFactory.CreateClient<SchedulerManagementClient>(profile, subscription, AzureEnvironment.Endpoint.ServiceManagement);
//Get RP properties
IDictionary<string, string> dict = schedulerManagementClient.GetResourceProviderProperties().Properties;
//Get available regions
string val = string.Empty;
if (dict.TryGetValue(SupportedRegionsKey, out val))
{
AvailableRegions = new List<string>();
val.Split(',').ToList().ForEach(s => AvailableRegions.Add(s));
}
//Store global counts for max jobs and min recurrence for each plan
if (dict.TryGetValue(FreeMaxJobCountKey, out val))
FreeMaxJobCountValue = Convert.ToInt32(dict[FreeMaxJobCountKey]);
if (dict.TryGetValue(FreeMinRecurrenceKey, out val))
FreeMinRecurrenceValue = TimeSpan.Parse(dict[FreeMinRecurrenceKey]);
if (dict.TryGetValue(StandardMaxJobCountKey, out val))
StandardMaxJobCountValue = Convert.ToInt32(dict[StandardMaxJobCountKey]);
if (dict.TryGetValue(StandardMinRecurrenceKey, out val))
StandardMinRecurrenceValue = TimeSpan.Parse(dict[StandardMinRecurrenceKey]);
if (dict.TryGetValue(PremiumMaxJobCountKey, out val))
PremiumMaxJobCountValue = Convert.ToInt32(dict[PremiumMaxJobCountKey]);
if (dict.TryGetValue(PremiumMinRecurrenceKey, out val))
PremiumMinRecurrenceValue = TimeSpan.Parse(dict[PremiumMinRecurrenceKey]);
}
#region Get Available Regions
public List<string> GetAvailableRegions()
{
return AvailableRegions;
}
#endregion
#region Job Collections
public List<PSJobCollection> GetJobCollection(string region = "", string jobCollection = "")
{
List<PSJobCollection> lstSchedulerJobCollection = new List<PSJobCollection>();
CloudServiceListResponse csList = csmClient.CloudServices.List();
if (!string.IsNullOrEmpty(region))
{
if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
string cloudService = region.ToCloudServiceName();
foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
{
if (cs.Name.Equals(cloudService, StringComparison.OrdinalIgnoreCase))
{
GetSchedulerJobCollection(cs, jobCollection).ForEach(x => lstSchedulerJobCollection.Add(x));
//If job collection parameter was passed and we found a matching job collection already, exit out of the loop and return the job collection
if (!string.IsNullOrEmpty(jobCollection) && lstSchedulerJobCollection.Count > 0)
return lstSchedulerJobCollection;
}
}
}
else if (string.IsNullOrEmpty(region))
{
foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
{
if (cs.Name.Equals(Constants.CloudServiceNameFirst + cs.GeoRegion.Replace(" ", string.Empty) + Constants.CloudServiceNameSecond, StringComparison.OrdinalIgnoreCase))
{
GetSchedulerJobCollection(cs, jobCollection).ForEach(x => lstSchedulerJobCollection.Add(x));
//If job collection parameter was passed and we found a matching job collection already, exit out of the loop and return the job collection
if (!string.IsNullOrEmpty(jobCollection) && lstSchedulerJobCollection.Count > 0)
return lstSchedulerJobCollection;
}
}
}
return lstSchedulerJobCollection;
}
private List<PSJobCollection> GetSchedulerJobCollection(CloudServiceListResponse.CloudService cloudService, string jobCollection)
{
List<PSJobCollection> lstSchedulerJobCollection = new List<PSJobCollection>();
foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cloudService.Name).Resources)
{
if (csRes.Type.Contains(Constants.JobCollectionResource))
{
JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cloudService.Name, csRes.Name);
if (string.IsNullOrEmpty(jobCollection) || (!string.IsNullOrEmpty(jobCollection) && jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase)))
{
PSJobCollection jc = new PSJobCollection
{
CloudServiceName = cloudService.Name,
JobCollectionName = jcGetResponse.Name,
State = Enum.GetName(typeof(JobCollectionState), jcGetResponse.State),
Location = cloudService.GeoRegion,
Uri = csmClient.BaseUri.AbsoluteUri + csmClient.Credentials.SubscriptionId + "cloudservices/" + cloudService.Name + Constants.JobCollectionResourceURL + jcGetResponse.Name
};
if (jcGetResponse.IntrinsicSettings != null)
{
jc.Plan = Enum.GetName(typeof(JobCollectionPlan), jcGetResponse.IntrinsicSettings.Plan);
if (jcGetResponse.IntrinsicSettings.Quota != null)
{
jc.MaxJobCount = jcGetResponse.IntrinsicSettings.Quota.MaxJobCount == null ? string.Empty : jcGetResponse.IntrinsicSettings.Quota.MaxJobCount.ToString();
jc.MaxRecurrence = jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence == null ? string.Empty : jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString() + " per " +
jcGetResponse.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString();
}
}
lstSchedulerJobCollection.Add(jc);
}
}
}
return lstSchedulerJobCollection;
}
#endregion
#region Scheduler Jobs
public List<PSSchedulerJob> GetJob(string region, string jobCollection, string job = "", string state = "")
{
if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
List<PSSchedulerJob> lstJob = new List<PSSchedulerJob>();
string cloudService = region.ToCloudServiceName();
if (!string.IsNullOrEmpty(job))
{
PSJobDetail jobDetail = GetJobDetail(jobCollection, job, cloudService);
if (string.IsNullOrEmpty(state) || (!string.IsNullOrEmpty(state) && jobDetail.Status.Equals(state, StringComparison.OrdinalIgnoreCase)))
{
lstJob.Add(jobDetail);
return lstJob;
}
}
else if (string.IsNullOrEmpty(job))
{
GetSchedulerJobs(cloudService, jobCollection).ForEach(x =>
{
if (string.IsNullOrEmpty(state) || (!string.IsNullOrEmpty(state) && x.Status.Equals(state, StringComparison.OrdinalIgnoreCase)))
{
lstJob.Add(x);
}
});
}
return lstJob;
}
private List<PSSchedulerJob> GetSchedulerJobs(string cloudService, string jobCollection)
{
List<PSSchedulerJob> lstJobs = new List<PSSchedulerJob>();
CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
{
if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
{
SchedulerClient schedClient = AzureSession.Instance.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);
JobListResponse jobs = schedClient.Jobs.List(new JobListParameters
{
Skip = 0,
});
foreach (Job job in jobs)
{
lstJobs.Add(new PSSchedulerJob
{
JobName = job.Id,
Lastrun = job.Status == null ? null : job.Status.LastExecutionTime,
Nextrun = job.Status == null ? null : job.Status.NextExecutionTime,
Status = job.State.ToString(),
StartTime = job.StartTime,
Recurrence = job.Recurrence == null ? string.Empty : job.Recurrence.Interval.ToString() + " per " + job.Recurrence.Frequency.ToString(),
Failures = job.Status == null ? default(int?) : job.Status.FailureCount,
Faults = job.Status == null ? default(int?) : job.Status.FaultedCount,
Executions = job.Status == null ? default(int?) : job.Status.ExecutionCount,
EndSchedule = GetEndTime(job),
JobCollectionName = jobCollection
});
}
}
}
return lstJobs;
}
private string GetEndTime(Job job)
{
if (job.Recurrence == null)
return "Run once";
else if (job.Recurrence != null)
{
if (job.Recurrence.Count == null)
return "None";
if (job.Recurrence.Count != null)
return "Until " + job.Recurrence.Count + " executions";
else
return job.Recurrence.Interval + " executions every " + job.Recurrence.Frequency.ToString();
}
return null;
}
#endregion
#region Job History
public List<PSJobHistory> GetJobHistory(string jobCollection, string job, string region, string jobStatus = "")
{
if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
List<PSJobHistory> lstPSJobHistory = new List<PSJobHistory>();
string cloudService = region.ToCloudServiceName();
CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
{
if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.InvariantCultureIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
{
SchedulerClient schedClient = AzureSession.Instance.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection.Trim(), csmClient.Credentials, schedulerManagementClient.BaseUri);
List<JobGetHistoryResponse.JobHistoryEntry> lstHistory = new List<JobGetHistoryResponse.JobHistoryEntry>();
int currentTop = 100;
if (string.IsNullOrEmpty(jobStatus))
{
JobGetHistoryResponse history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100 });
lstHistory.AddRange(history.JobHistory);
while (history.JobHistory.Count > 99)
{
history = schedClient.Jobs.GetHistory(job.Trim(), new JobGetHistoryParameters { Top = 100, Skip = currentTop });
currentTop += 100;
lstHistory.AddRange(history.JobHistory);
}
}
else if (!string.IsNullOrEmpty(jobStatus))
{
JobHistoryStatus status = jobStatus.Equals("Completed") ? JobHistoryStatus.Completed : JobHistoryStatus.Failed;
JobGetHistoryResponse history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Status = status });
lstHistory.AddRange(history.JobHistory);
while (history.JobHistory.Count > 99)
{
history = schedClient.Jobs.GetHistoryWithFilter(job.Trim(), new JobGetHistoryWithFilterParameters { Top = 100, Skip = currentTop });
currentTop += 100;
lstHistory.AddRange(history.JobHistory);
}
}
foreach (JobGetHistoryResponse.JobHistoryEntry entry in lstHistory)
{
PSJobHistory historyObj = new PSJobHistory();
historyObj.Status = entry.Status.ToString();
historyObj.StartTime = entry.StartTime;
historyObj.EndTime = entry.EndTime;
historyObj.JobName = entry.Id;
historyObj.Details = GetHistoryDetails(entry.Message);
historyObj.Retry = entry.RetryCount;
historyObj.Occurence = entry.RepeatCount;
if (JobHistoryActionName.ErrorAction == entry.ActionName)
{
PSJobHistoryError errorObj = historyObj.ToJobHistoryError();
errorObj.ErrorAction = JobHistoryActionName.ErrorAction.ToString();
lstPSJobHistory.Add(errorObj);
}
else
lstPSJobHistory.Add(historyObj);
}
}
}
return lstPSJobHistory;
}
private PSJobHistoryDetail GetHistoryDetails(string message)
{
PSJobHistoryDetail detail = new PSJobHistoryDetail();
if (message.Contains("Http Action -"))
{
PSJobHistoryHttpDetail details = new PSJobHistoryHttpDetail { ActionType = "http" };
if (message.Contains("Request to host") && message.Contains("failed:"))
{
int firstIndex = message.IndexOf("'");
int secondIndex = message.IndexOf("'", firstIndex + 1);
details.HostName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1));
details.Response = "Failed";
details.ResponseBody = message;
}
else
{
int firstIndex = message.IndexOf("'");
int secondIndex = message.IndexOf("'", firstIndex + 1);
int thirdIndex = message.IndexOf("'", secondIndex + 1);
int fourthIndex = message.IndexOf("'", thirdIndex + 1);
details.HostName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1));
details.Response = message.Substring(thirdIndex + 1, fourthIndex - (thirdIndex + 1));
int bodyIndex = message.IndexOf("Body: ");
details.ResponseBody = message.Substring(bodyIndex + 6);
}
return details;
}
else if (message.Contains("StorageQueue Action -"))
{
PSJobHistoryStorageDetail details = new PSJobHistoryStorageDetail { ActionType = "Storage" };
if (message.Contains("does not exist"))
{
int firstIndex = message.IndexOf("'");
int secondIndex = message.IndexOf("'", firstIndex + 1);
details.StorageAccountName = string.Empty;
details.StorageQueueName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1));
details.ResponseBody = message;
details.ResponseStatus = "Failed";
}
else
{
int firstIndex = message.IndexOf("'");
int secondIndex = message.IndexOf("'", firstIndex + 1);
int thirdIndex = message.IndexOf("'", secondIndex + 1);
int fourthIndex = message.IndexOf("'", thirdIndex + 1);
details.StorageAccountName = message.Substring(firstIndex + 1, secondIndex - (firstIndex + 1));
details.StorageQueueName = message.Substring(thirdIndex + 1, fourthIndex - (thirdIndex + 1));
details.ResponseStatus = message.Substring(fourthIndex + 2);
details.ResponseBody = message;
}
return details;
}
return detail;
}
#endregion
#region Get Job Details
public PSJobDetail GetJobDetail(string jobCollection, string job, string cloudService)
{
CloudServiceGetResponse csDetails = csmClient.CloudServices.Get(cloudService);
foreach (CloudServiceGetResponse.Resource csRes in csDetails.Resources)
{
if (csRes.ResourceProviderNamespace.Equals(Constants.SchedulerRPNameProvider, StringComparison.OrdinalIgnoreCase) && csRes.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
{
SchedulerClient schedClient = AzureSession.Instance.ClientFactory.CreateCustomClient<SchedulerClient>(cloudService, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);
JobListResponse jobs = schedClient.Jobs.List(new JobListParameters
{
Skip = 0,
});
foreach (Job j in jobs)
{
if (j.Id.ToLower().Equals(job.ToLower()))
{
if (Enum.GetName(typeof(JobActionType), j.Action.Type).Contains("Http"))
{
PSHttpJobDetail jobDetail = new PSHttpJobDetail();
jobDetail.JobName = j.Id;
jobDetail.JobCollectionName = jobCollection;
jobDetail.CloudService = cloudService;
jobDetail.ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type);
jobDetail.Uri = j.Action.Request.Uri;
jobDetail.Method = j.Action.Request.Method;
jobDetail.Body = j.Action.Request.Body;
jobDetail.Headers = j.Action.Request.Headers;
jobDetail.Status = j.State.ToString();
jobDetail.StartTime = j.StartTime;
jobDetail.EndSchedule = GetEndTime(j);
jobDetail.Recurrence = j.Recurrence == null ? string.Empty : j.Recurrence.Interval.ToString() + " (" + j.Recurrence.Frequency.ToString() + "s)";
if (j.Status != null)
{
jobDetail.Failures = j.Status.FailureCount;
jobDetail.Faults = j.Status.FaultedCount;
jobDetail.Executions = j.Status.ExecutionCount;
jobDetail.Lastrun = j.Status.LastExecutionTime;
jobDetail.Nextrun = j.Status.NextExecutionTime;
}
if (j.Action.Request.Authentication != null)
{
switch(j.Action.Request.Authentication.Type)
{
case HttpAuthenticationType.ClientCertificate:
PSClientCertAuthenticationJobDetail ClientCertJobDetail = new PSClientCertAuthenticationJobDetail(jobDetail);
ClientCertJobDetail.ClientCertExpiryDate = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateExpiration.ToString();
ClientCertJobDetail.ClientCertSubjectName = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateSubjectName;
ClientCertJobDetail.ClientCertThumbprint = ((j.Action.Request.Authentication) as ClientCertAuthentication).CertificateThumbprint;
return ClientCertJobDetail;
case HttpAuthenticationType.ActiveDirectoryOAuth:
PSAADOAuthenticationJobDetail AADOAuthJobDetail = new PSAADOAuthenticationJobDetail(jobDetail);
AADOAuthJobDetail.Audience = ((j.Action.Request.Authentication) as AADOAuthAuthentication).Audience;
AADOAuthJobDetail.ClientId = ((j.Action.Request.Authentication) as AADOAuthAuthentication).ClientId;
AADOAuthJobDetail.Tenant = ((j.Action.Request.Authentication) as AADOAuthAuthentication).Tenant;
return AADOAuthJobDetail;
case HttpAuthenticationType.Basic:
PSBasicAuthenticationJobDetail BasicAuthJobDetail = new PSBasicAuthenticationJobDetail(jobDetail);
BasicAuthJobDetail.Username = ((j.Action.Request.Authentication) as BasicAuthentication).Username;
return BasicAuthJobDetail;
}
}
return jobDetail;
}
else
{
return new PSStorageQueueJobDetail
{
JobName = j.Id,
JobCollectionName = jobCollection,
CloudService = cloudService,
ActionType = Enum.GetName(typeof(JobActionType), j.Action.Type),
StorageAccountName = j.Action.QueueMessage.StorageAccountName,
StorageQueueName = j.Action.QueueMessage.QueueName,
SasToken = j.Action.QueueMessage.SasToken,
QueueMessage = j.Action.QueueMessage.Message,
Status = j.State.ToString(),
EndSchedule = GetEndTime(j),
StartTime = j.StartTime,
Recurrence = j.Recurrence == null ? string.Empty : j.Recurrence.Interval.ToString() + " (" + j.Recurrence.Frequency.ToString() + "s)",
Failures = j.Status == null ? default(int?) : j.Status.FailureCount,
Faults = j.Status == null ? default(int?) : j.Status.FaultedCount,
Executions = j.Status == null ? default(int?) : j.Status.ExecutionCount,
Lastrun = j.Status == null ? null : j.Status.LastExecutionTime,
Nextrun = j.Status == null ? null : j.Status.NextExecutionTime
};
}
}
}
}
}
return null;
}
#endregion
#region Delete Jobs
public bool DeleteJob(string jobCollection, string jobName, string region = "")
{
if (!string.IsNullOrEmpty(region))
{
if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerClient schedClient = AzureSession.Instance.ClientFactory.CreateCustomClient<SchedulerClient>(region.ToCloudServiceName(), jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);
AzureOperationResponse response = schedClient.Jobs.Delete(jobName);
return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
}
else if (string.IsNullOrEmpty(region))
{
CloudServiceListResponse csList = csmClient.CloudServices.List();
foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
{
foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources)
{
if (csRes.Type.Contains(Constants.JobCollectionResource))
{
JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name);
if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
{
foreach (PSSchedulerJob job in GetSchedulerJobs(cs.Name, jobCollection))
{
if (job.JobName.Equals(jobName, StringComparison.OrdinalIgnoreCase))
{
SchedulerClient schedClient = AzureSession.Instance.ClientFactory.CreateCustomClient<SchedulerClient>(cs.Name, jobCollection, csmClient.Credentials, schedulerManagementClient.BaseUri);
AzureOperationResponse response = schedClient.Jobs.Delete(jobName);
return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
}
}
}
}
}
}
}
return false;
}
#endregion
#region Delete Job Collection
public bool DeleteJobCollection(string jobCollection, string region = "")
{
if (!string.IsNullOrEmpty(region))
{
if (!this.AvailableRegions.Contains(region, StringComparer.OrdinalIgnoreCase))
throw new Exception(Resources.SchedulerInvalidLocation);
SchedulerOperationStatusResponse response = schedulerManagementClient.JobCollections.Delete(region.ToCloudServiceName(), jobCollection);
return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
}
else if (string.IsNullOrEmpty(region))
{
CloudServiceListResponse csList = csmClient.CloudServices.List();
foreach (CloudServiceListResponse.CloudService cs in csList.CloudServices)
{
foreach (CloudServiceGetResponse.Resource csRes in csmClient.CloudServices.Get(cs.Name).Resources)
{
if (csRes.Type.Contains(Constants.JobCollectionResource))
{
JobCollectionGetResponse jcGetResponse = schedulerManagementClient.JobCollections.Get(cs.Name, csRes.Name);
if (jcGetResponse.Name.Equals(jobCollection, StringComparison.OrdinalIgnoreCase))
{
SchedulerOperationStatusResponse response = schedulerManagementClient.JobCollections.Delete(region.ToCloudServiceName(), jobCollection);
return response.StatusCode == System.Net.HttpStatusCode.OK ? true : false;
}
}
}
}
}
return false;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Security.AccessControl
{
[System.FlagsAttribute]
public enum AccessControlActions
{
Change = 2,
None = 0,
View = 1,
}
public enum AccessControlModification
{
Add = 0,
Remove = 3,
RemoveAll = 4,
RemoveSpecific = 5,
Reset = 2,
Set = 1,
}
[System.FlagsAttribute]
public enum AccessControlSections
{
Access = 2,
All = 15,
Audit = 1,
Group = 8,
None = 0,
Owner = 4,
}
public enum AccessControlType
{
Allow = 0,
Deny = 1,
}
public abstract partial class AccessRule : System.Security.AccessControl.AuthorizationRule
{
protected AccessRule(System.Security.Principal.IdentityReference identity, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags)) { }
public System.Security.AccessControl.AccessControlType AccessControlType { get { return default(System.Security.AccessControl.AccessControlType); } }
}
public partial class AccessRule<T> : System.Security.AccessControl.AccessRule where T : struct
{
public AccessRule(System.Security.Principal.IdentityReference identity, T rights, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { }
public AccessRule(System.Security.Principal.IdentityReference identity, T rights, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { }
public AccessRule(string identity, T rights, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { }
public AccessRule(string identity, T rights, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { }
public T Rights { get { return default(T); } }
}
public sealed partial class AceEnumerator : System.Collections.IEnumerator
{
internal AceEnumerator() { }
public System.Security.AccessControl.GenericAce Current { get { return default(System.Security.AccessControl.GenericAce); } }
object System.Collections.IEnumerator.Current { get { return default(object); } }
public bool MoveNext() { return default(bool); }
public void Reset() { }
}
[System.FlagsAttribute]
public enum AceFlags : byte
{
AuditFlags = (byte)192,
ContainerInherit = (byte)2,
FailedAccess = (byte)128,
InheritanceFlags = (byte)15,
Inherited = (byte)16,
InheritOnly = (byte)8,
None = (byte)0,
NoPropagateInherit = (byte)4,
ObjectInherit = (byte)1,
SuccessfulAccess = (byte)64,
}
public enum AceQualifier
{
AccessAllowed = 0,
AccessDenied = 1,
SystemAlarm = 3,
SystemAudit = 2,
}
public enum AceType : byte
{
AccessAllowed = (byte)0,
AccessAllowedCallback = (byte)9,
AccessAllowedCallbackObject = (byte)11,
AccessAllowedCompound = (byte)4,
AccessAllowedObject = (byte)5,
AccessDenied = (byte)1,
AccessDeniedCallback = (byte)10,
AccessDeniedCallbackObject = (byte)12,
AccessDeniedObject = (byte)6,
MaxDefinedAceType = (byte)16,
SystemAlarm = (byte)3,
SystemAlarmCallback = (byte)14,
SystemAlarmCallbackObject = (byte)16,
SystemAlarmObject = (byte)8,
SystemAudit = (byte)2,
SystemAuditCallback = (byte)13,
SystemAuditCallbackObject = (byte)15,
SystemAuditObject = (byte)7,
}
[System.FlagsAttribute]
public enum AuditFlags
{
Failure = 2,
None = 0,
Success = 1,
}
public abstract partial class AuditRule : System.Security.AccessControl.AuthorizationRule
{
protected AuditRule(System.Security.Principal.IdentityReference identity, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AuditFlags auditFlags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags)) { }
public System.Security.AccessControl.AuditFlags AuditFlags { get { return default(System.Security.AccessControl.AuditFlags); } }
}
public partial class AuditRule<T> : System.Security.AccessControl.AuditRule where T : struct
{
public AuditRule(System.Security.Principal.IdentityReference identity, T rights, System.Security.AccessControl.AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { }
public AuditRule(System.Security.Principal.IdentityReference identity, T rights, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { }
public AuditRule(string identity, T rights, System.Security.AccessControl.AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { }
public AuditRule(string identity, T rights, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AuditFlags flags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { }
public T Rights { get { return default(T); } }
}
public abstract partial class AuthorizationRule
{
protected internal AuthorizationRule(System.Security.Principal.IdentityReference identity, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
protected internal int AccessMask { get { return default(int); } }
public System.Security.Principal.IdentityReference IdentityReference { get { return default(System.Security.Principal.IdentityReference); } }
public System.Security.AccessControl.InheritanceFlags InheritanceFlags { get { return default(System.Security.AccessControl.InheritanceFlags); } }
public bool IsInherited { get { return default(bool); } }
public System.Security.AccessControl.PropagationFlags PropagationFlags { get { return default(System.Security.AccessControl.PropagationFlags); } }
}
public sealed partial class AuthorizationRuleCollection
{
public AuthorizationRuleCollection() { }
public System.Security.AccessControl.AuthorizationRule this[int index] { get { return default(System.Security.AccessControl.AuthorizationRule); } }
public void AddRule(System.Security.AccessControl.AuthorizationRule rule) { }
public void CopyTo(System.Security.AccessControl.AuthorizationRule[] rules, int index) { }
}
public sealed partial class CommonAce : System.Security.AccessControl.QualifiedAce
{
public CommonAce(System.Security.AccessControl.AceFlags flags, System.Security.AccessControl.AceQualifier qualifier, int accessMask, System.Security.Principal.SecurityIdentifier sid, bool isCallback, byte[] opaque) { }
public override int BinaryLength { get { return default(int); } }
public override void GetBinaryForm(byte[] binaryForm, int offset) { }
public static int MaxOpaqueLength(bool isCallback) { return default(int); }
}
public abstract partial class CommonAcl : System.Security.AccessControl.GenericAcl
{
internal CommonAcl() { }
public sealed override int BinaryLength { get { return default(int); } }
public sealed override int Count { get { return default(int); } }
public bool IsCanonical { get { return default(bool); } }
public bool IsContainer { get { return default(bool); } }
public bool IsDS { get { return default(bool); } }
public sealed override System.Security.AccessControl.GenericAce this[int index] { get { return default(System.Security.AccessControl.GenericAce); } set { } }
public sealed override byte Revision { get { return default(byte); } }
public sealed override void GetBinaryForm(byte[] binaryForm, int offset) { }
public void Purge(System.Security.Principal.SecurityIdentifier sid) { }
public void RemoveInheritedAces() { }
}
public abstract partial class CommonObjectSecurity : System.Security.AccessControl.ObjectSecurity
{
protected CommonObjectSecurity(bool isContainer) { }
protected void AddAccessRule(System.Security.AccessControl.AccessRule rule) { }
protected void AddAuditRule(System.Security.AccessControl.AuditRule rule) { }
public System.Security.AccessControl.AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, System.Type targetType) { return default(System.Security.AccessControl.AuthorizationRuleCollection); }
public System.Security.AccessControl.AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, System.Type targetType) { return default(System.Security.AccessControl.AuthorizationRuleCollection); }
protected override bool ModifyAccess(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AccessRule rule, out bool modified) { modified = default(bool); return default(bool); }
protected override bool ModifyAudit(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AuditRule rule, out bool modified) { modified = default(bool); return default(bool); }
protected bool RemoveAccessRule(System.Security.AccessControl.AccessRule rule) { return default(bool); }
protected void RemoveAccessRuleAll(System.Security.AccessControl.AccessRule rule) { }
protected void RemoveAccessRuleSpecific(System.Security.AccessControl.AccessRule rule) { }
protected bool RemoveAuditRule(System.Security.AccessControl.AuditRule rule) { return default(bool); }
protected void RemoveAuditRuleAll(System.Security.AccessControl.AuditRule rule) { }
protected void RemoveAuditRuleSpecific(System.Security.AccessControl.AuditRule rule) { }
protected void ResetAccessRule(System.Security.AccessControl.AccessRule rule) { }
protected void SetAccessRule(System.Security.AccessControl.AccessRule rule) { }
protected void SetAuditRule(System.Security.AccessControl.AuditRule rule) { }
}
public sealed partial class CommonSecurityDescriptor : System.Security.AccessControl.GenericSecurityDescriptor
{
public CommonSecurityDescriptor(bool isContainer, bool isDS, byte[] binaryForm, int offset) { }
public CommonSecurityDescriptor(bool isContainer, bool isDS, System.Security.AccessControl.ControlFlags flags, System.Security.Principal.SecurityIdentifier owner, System.Security.Principal.SecurityIdentifier group, System.Security.AccessControl.SystemAcl systemAcl, System.Security.AccessControl.DiscretionaryAcl discretionaryAcl) { }
public CommonSecurityDescriptor(bool isContainer, bool isDS, System.Security.AccessControl.RawSecurityDescriptor rawSecurityDescriptor) { }
public CommonSecurityDescriptor(bool isContainer, bool isDS, string sddlForm) { }
public override System.Security.AccessControl.ControlFlags ControlFlags { get { return default(System.Security.AccessControl.ControlFlags); } }
public System.Security.AccessControl.DiscretionaryAcl DiscretionaryAcl { get { return default(System.Security.AccessControl.DiscretionaryAcl); } set { } }
public override System.Security.Principal.SecurityIdentifier Group { get { return default(System.Security.Principal.SecurityIdentifier); } set { } }
public bool IsContainer { get { return default(bool); } }
public bool IsDiscretionaryAclCanonical { get { return default(bool); } }
public bool IsDS { get { return default(bool); } }
public bool IsSystemAclCanonical { get { return default(bool); } }
public override System.Security.Principal.SecurityIdentifier Owner { get { return default(System.Security.Principal.SecurityIdentifier); } set { } }
public System.Security.AccessControl.SystemAcl SystemAcl { get { return default(System.Security.AccessControl.SystemAcl); } set { } }
public void AddDiscretionaryAcl(byte revision, int trusted) { }
public void AddSystemAcl(byte revision, int trusted) { }
public void PurgeAccessControl(System.Security.Principal.SecurityIdentifier sid) { }
public void PurgeAudit(System.Security.Principal.SecurityIdentifier sid) { }
public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInheritance) { }
public void SetSystemAclProtection(bool isProtected, bool preserveInheritance) { }
}
public sealed partial class CompoundAce : System.Security.AccessControl.KnownAce
{
public CompoundAce(System.Security.AccessControl.AceFlags flags, int accessMask, System.Security.AccessControl.CompoundAceType compoundAceType, System.Security.Principal.SecurityIdentifier sid) { }
public override int BinaryLength { get { return default(int); } }
public System.Security.AccessControl.CompoundAceType CompoundAceType { get { return default(System.Security.AccessControl.CompoundAceType); } set { } }
public override void GetBinaryForm(byte[] binaryForm, int offset) { }
}
public enum CompoundAceType
{
Impersonation = 1,
}
[System.FlagsAttribute]
public enum ControlFlags
{
DiscretionaryAclAutoInherited = 1024,
DiscretionaryAclAutoInheritRequired = 256,
DiscretionaryAclDefaulted = 8,
DiscretionaryAclPresent = 4,
DiscretionaryAclProtected = 4096,
DiscretionaryAclUntrusted = 64,
GroupDefaulted = 2,
None = 0,
OwnerDefaulted = 1,
RMControlValid = 16384,
SelfRelative = 32768,
ServerSecurity = 128,
SystemAclAutoInherited = 2048,
SystemAclAutoInheritRequired = 512,
SystemAclDefaulted = 32,
SystemAclPresent = 16,
SystemAclProtected = 8192,
}
public sealed partial class CustomAce : System.Security.AccessControl.GenericAce
{
public static readonly int MaxOpaqueLength;
public CustomAce(System.Security.AccessControl.AceType type, System.Security.AccessControl.AceFlags flags, byte[] opaque) { }
public override int BinaryLength { get { return default(int); } }
public int OpaqueLength { get { return default(int); } }
public override void GetBinaryForm(byte[] binaryForm, int offset) { }
public byte[] GetOpaque() { return default(byte[]); }
public void SetOpaque(byte[] opaque) { }
}
public sealed partial class DiscretionaryAcl : System.Security.AccessControl.CommonAcl
{
public DiscretionaryAcl(bool isContainer, bool isDS, byte revision, int capacity) { }
public DiscretionaryAcl(bool isContainer, bool isDS, int capacity) { }
public DiscretionaryAcl(bool isContainer, bool isDS, System.Security.AccessControl.RawAcl rawAcl) { }
public void AddAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void AddAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void AddAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAccessRule rule) { }
public bool RemoveAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { return default(bool); }
public bool RemoveAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { return default(bool); }
public bool RemoveAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAccessRule rule) { return default(bool); }
public void RemoveAccessSpecific(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void RemoveAccessSpecific(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void RemoveAccessSpecific(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAccessRule rule) { }
public void SetAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void SetAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void SetAccess(System.Security.AccessControl.AccessControlType accessType, System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAccessRule rule) { }
}
public abstract partial class GenericAce
{
internal GenericAce() { }
public System.Security.AccessControl.AceFlags AceFlags { get { return default(System.Security.AccessControl.AceFlags); } set { } }
public System.Security.AccessControl.AceType AceType { get { return default(System.Security.AccessControl.AceType); } }
public System.Security.AccessControl.AuditFlags AuditFlags { get { return default(System.Security.AccessControl.AuditFlags); } }
public abstract int BinaryLength { get; }
public System.Security.AccessControl.InheritanceFlags InheritanceFlags { get { return default(System.Security.AccessControl.InheritanceFlags); } }
public bool IsInherited { get { return default(bool); } }
public System.Security.AccessControl.PropagationFlags PropagationFlags { get { return default(System.Security.AccessControl.PropagationFlags); } }
public System.Security.AccessControl.GenericAce Copy() { return default(System.Security.AccessControl.GenericAce); }
public static System.Security.AccessControl.GenericAce CreateFromBinaryForm(byte[] binaryForm, int offset) { return default(System.Security.AccessControl.GenericAce); }
public sealed override bool Equals(object o) { return default(bool); }
public abstract void GetBinaryForm(byte[] binaryForm, int offset);
public sealed override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.AccessControl.GenericAce left, System.Security.AccessControl.GenericAce right) { return default(bool); }
public static bool operator !=(System.Security.AccessControl.GenericAce left, System.Security.AccessControl.GenericAce right) { return default(bool); }
}
public abstract partial class GenericAcl : System.Collections.ICollection, System.Collections.IEnumerable
{
public static readonly byte AclRevision;
public static readonly byte AclRevisionDS;
public static readonly int MaxBinaryLength;
protected GenericAcl() { }
public abstract int BinaryLength { get; }
public abstract int Count { get; }
public bool IsSynchronized { get { return default(bool); } }
public abstract System.Security.AccessControl.GenericAce this[int index] { get; set; }
public abstract byte Revision { get; }
public virtual object SyncRoot { get { return default(object); } }
public void CopyTo(System.Security.AccessControl.GenericAce[] array, int index) { }
public abstract void GetBinaryForm(byte[] binaryForm, int offset);
public System.Security.AccessControl.AceEnumerator GetEnumerator() { return default(System.Security.AccessControl.AceEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
public abstract partial class GenericSecurityDescriptor
{
protected GenericSecurityDescriptor() { }
public int BinaryLength { get { return default(int); } }
public abstract System.Security.AccessControl.ControlFlags ControlFlags { get; }
public abstract System.Security.Principal.SecurityIdentifier Group { get; set; }
public abstract System.Security.Principal.SecurityIdentifier Owner { get; set; }
public static byte Revision { get { return default(byte); } }
public void GetBinaryForm(byte[] binaryForm, int offset) { }
public string GetSddlForm(System.Security.AccessControl.AccessControlSections includeSections) { return default(string); }
public static bool IsSddlConversionSupported() { return default(bool); }
}
[System.FlagsAttribute]
public enum InheritanceFlags
{
ContainerInherit = 1,
None = 0,
ObjectInherit = 2,
}
public abstract partial class KnownAce : System.Security.AccessControl.GenericAce
{
internal KnownAce() { }
public int AccessMask { get { return default(int); } set { } }
public System.Security.Principal.SecurityIdentifier SecurityIdentifier { get { return default(System.Security.Principal.SecurityIdentifier); } set { } }
}
public abstract partial class NativeObjectSecurity : System.Security.AccessControl.CommonObjectSecurity
{
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType) : base(default(bool)) { }
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, System.Runtime.InteropServices.SafeHandle handle, System.Security.AccessControl.AccessControlSections includeSections) : base(default(bool)) { }
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, System.Runtime.InteropServices.SafeHandle handle, System.Security.AccessControl.AccessControlSections includeSections, System.Security.AccessControl.NativeObjectSecurity.ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(default(bool)) { }
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, System.Security.AccessControl.NativeObjectSecurity.ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(default(bool)) { }
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, string name, System.Security.AccessControl.AccessControlSections includeSections) : base(default(bool)) { }
protected NativeObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, string name, System.Security.AccessControl.AccessControlSections includeSections, System.Security.AccessControl.NativeObjectSecurity.ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(default(bool)) { }
protected sealed override void Persist(System.Runtime.InteropServices.SafeHandle handle, System.Security.AccessControl.AccessControlSections includeSections) { }
protected void Persist(System.Runtime.InteropServices.SafeHandle handle, System.Security.AccessControl.AccessControlSections includeSections, object exceptionContext) { }
protected sealed override void Persist(string name, System.Security.AccessControl.AccessControlSections includeSections) { }
protected void Persist(string name, System.Security.AccessControl.AccessControlSections includeSections, object exceptionContext) { }
protected internal delegate System.Exception ExceptionFromErrorCode(int errorCode, string name, System.Runtime.InteropServices.SafeHandle handle, object context);
}
public abstract partial class ObjectAccessRule : System.Security.AccessControl.AccessRule
{
protected ObjectAccessRule(System.Security.Principal.IdentityReference identity, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Guid objectType, System.Guid inheritedObjectType, System.Security.AccessControl.AccessControlType type) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AccessControlType)) { }
public System.Guid InheritedObjectType { get { return default(System.Guid); } }
public System.Security.AccessControl.ObjectAceFlags ObjectFlags { get { return default(System.Security.AccessControl.ObjectAceFlags); } }
public System.Guid ObjectType { get { return default(System.Guid); } }
}
public sealed partial class ObjectAce : System.Security.AccessControl.QualifiedAce
{
public ObjectAce(System.Security.AccessControl.AceFlags aceFlags, System.Security.AccessControl.AceQualifier qualifier, int accessMask, System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAceFlags flags, System.Guid type, System.Guid inheritedType, bool isCallback, byte[] opaque) { }
public override int BinaryLength { get { return default(int); } }
public System.Guid InheritedObjectAceType { get { return default(System.Guid); } set { } }
public System.Security.AccessControl.ObjectAceFlags ObjectAceFlags { get { return default(System.Security.AccessControl.ObjectAceFlags); } set { } }
public System.Guid ObjectAceType { get { return default(System.Guid); } set { } }
public override void GetBinaryForm(byte[] binaryForm, int offset) { }
public static int MaxOpaqueLength(bool isCallback) { return default(int); }
}
[System.FlagsAttribute]
public enum ObjectAceFlags
{
InheritedObjectAceTypePresent = 2,
None = 0,
ObjectAceTypePresent = 1,
}
public abstract partial class ObjectAuditRule : System.Security.AccessControl.AuditRule
{
protected ObjectAuditRule(System.Security.Principal.IdentityReference identity, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Guid objectType, System.Guid inheritedObjectType, System.Security.AccessControl.AuditFlags auditFlags) : base(default(System.Security.Principal.IdentityReference), default(int), default(bool), default(System.Security.AccessControl.InheritanceFlags), default(System.Security.AccessControl.PropagationFlags), default(System.Security.AccessControl.AuditFlags)) { }
public System.Guid InheritedObjectType { get { return default(System.Guid); } }
public System.Security.AccessControl.ObjectAceFlags ObjectFlags { get { return default(System.Security.AccessControl.ObjectAceFlags); } }
public System.Guid ObjectType { get { return default(System.Guid); } }
}
public abstract partial class ObjectSecurity
{
protected ObjectSecurity() { }
protected ObjectSecurity(bool isContainer, bool isDS) { }
protected ObjectSecurity(System.Security.AccessControl.CommonSecurityDescriptor securityDescriptor) { }
public abstract System.Type AccessRightType { get; }
protected bool AccessRulesModified { get { return default(bool); } set { } }
public abstract System.Type AccessRuleType { get; }
public bool AreAccessRulesCanonical { get { return default(bool); } }
public bool AreAccessRulesProtected { get { return default(bool); } }
public bool AreAuditRulesCanonical { get { return default(bool); } }
public bool AreAuditRulesProtected { get { return default(bool); } }
protected bool AuditRulesModified { get { return default(bool); } set { } }
public abstract System.Type AuditRuleType { get; }
protected bool GroupModified { get { return default(bool); } set { } }
protected bool IsContainer { get { return default(bool); } }
protected bool IsDS { get { return default(bool); } }
protected bool OwnerModified { get { return default(bool); } set { } }
public abstract System.Security.AccessControl.AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AccessControlType type);
public abstract System.Security.AccessControl.AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AuditFlags flags);
public System.Security.Principal.IdentityReference GetGroup(System.Type targetType) { return default(System.Security.Principal.IdentityReference); }
public System.Security.Principal.IdentityReference GetOwner(System.Type targetType) { return default(System.Security.Principal.IdentityReference); }
public byte[] GetSecurityDescriptorBinaryForm() { return default(byte[]); }
public string GetSecurityDescriptorSddlForm(System.Security.AccessControl.AccessControlSections includeSections) { return default(string); }
public static bool IsSddlConversionSupported() { return default(bool); }
protected abstract bool ModifyAccess(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AccessRule rule, out bool modified);
public virtual bool ModifyAccessRule(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AccessRule rule, out bool modified) { modified = default(bool); return default(bool); }
protected abstract bool ModifyAudit(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AuditRule rule, out bool modified);
public virtual bool ModifyAuditRule(System.Security.AccessControl.AccessControlModification modification, System.Security.AccessControl.AuditRule rule, out bool modified) { modified = default(bool); return default(bool); }
protected virtual void Persist(bool enableOwnershipPrivilege, string name, System.Security.AccessControl.AccessControlSections includeSections) { }
protected virtual void Persist(System.Runtime.InteropServices.SafeHandle handle, System.Security.AccessControl.AccessControlSections includeSections) { }
protected virtual void Persist(string name, System.Security.AccessControl.AccessControlSections includeSections) { }
public virtual void PurgeAccessRules(System.Security.Principal.IdentityReference identity) { }
public virtual void PurgeAuditRules(System.Security.Principal.IdentityReference identity) { }
protected void ReadLock() { }
protected void ReadUnlock() { }
public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance) { }
public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance) { }
public void SetGroup(System.Security.Principal.IdentityReference identity) { }
public void SetOwner(System.Security.Principal.IdentityReference identity) { }
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm) { }
public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, System.Security.AccessControl.AccessControlSections includeSections) { }
public void SetSecurityDescriptorSddlForm(string sddlForm) { }
public void SetSecurityDescriptorSddlForm(string sddlForm, System.Security.AccessControl.AccessControlSections includeSections) { }
protected void WriteLock() { }
protected void WriteUnlock() { }
}
public abstract partial class ObjectSecurity<T> : System.Security.AccessControl.NativeObjectSecurity where T : struct
{
protected ObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType) : base(default(bool), default(System.Security.AccessControl.ResourceType)) { }
protected ObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, System.Runtime.InteropServices.SafeHandle safeHandle, System.Security.AccessControl.AccessControlSections includeSections) : base(default(bool), default(System.Security.AccessControl.ResourceType)) { }
protected ObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, System.Runtime.InteropServices.SafeHandle safeHandle, System.Security.AccessControl.AccessControlSections includeSections, System.Security.AccessControl.NativeObjectSecurity.ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(default(bool), default(System.Security.AccessControl.ResourceType)) { }
protected ObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, string name, System.Security.AccessControl.AccessControlSections includeSections) : base(default(bool), default(System.Security.AccessControl.ResourceType)) { }
protected ObjectSecurity(bool isContainer, System.Security.AccessControl.ResourceType resourceType, string name, System.Security.AccessControl.AccessControlSections includeSections, System.Security.AccessControl.NativeObjectSecurity.ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) : base(default(bool), default(System.Security.AccessControl.ResourceType)) { }
public override System.Type AccessRightType { get { return default(System.Type); } }
public override System.Type AccessRuleType { get { return default(System.Type); } }
public override System.Type AuditRuleType { get { return default(System.Type); } }
public override System.Security.AccessControl.AccessRule AccessRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AccessControlType type) { return default(System.Security.AccessControl.AccessRule); }
public virtual void AddAccessRule(System.Security.AccessControl.AccessRule<T> rule) { }
public virtual void AddAuditRule(System.Security.AccessControl.AuditRule<T> rule) { }
public override System.Security.AccessControl.AuditRule AuditRuleFactory(System.Security.Principal.IdentityReference identityReference, int accessMask, bool isInherited, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.AuditFlags flags) { return default(System.Security.AccessControl.AuditRule); }
protected internal void Persist(System.Runtime.InteropServices.SafeHandle handle) { }
protected internal void Persist(string name) { }
public virtual bool RemoveAccessRule(System.Security.AccessControl.AccessRule<T> rule) { return default(bool); }
public virtual void RemoveAccessRuleAll(System.Security.AccessControl.AccessRule<T> rule) { }
public virtual void RemoveAccessRuleSpecific(System.Security.AccessControl.AccessRule<T> rule) { }
public virtual bool RemoveAuditRule(System.Security.AccessControl.AuditRule<T> rule) { return default(bool); }
public virtual void RemoveAuditRuleAll(System.Security.AccessControl.AuditRule<T> rule) { }
public virtual void RemoveAuditRuleSpecific(System.Security.AccessControl.AuditRule<T> rule) { }
public virtual void ResetAccessRule(System.Security.AccessControl.AccessRule<T> rule) { }
public virtual void SetAccessRule(System.Security.AccessControl.AccessRule<T> rule) { }
public virtual void SetAuditRule(System.Security.AccessControl.AuditRule<T> rule) { }
}
public sealed partial class PrivilegeNotHeldException : System.UnauthorizedAccessException
{
public PrivilegeNotHeldException() { }
public PrivilegeNotHeldException(string privilege) { }
public PrivilegeNotHeldException(string privilege, System.Exception inner) { }
public string PrivilegeName { get { return default(string); } }
}
[System.FlagsAttribute]
public enum PropagationFlags
{
InheritOnly = 2,
None = 0,
NoPropagateInherit = 1,
}
public abstract partial class QualifiedAce : System.Security.AccessControl.KnownAce
{
internal QualifiedAce() { }
public System.Security.AccessControl.AceQualifier AceQualifier { get { return default(System.Security.AccessControl.AceQualifier); } }
public bool IsCallback { get { return default(bool); } }
public int OpaqueLength { get { return default(int); } }
public byte[] GetOpaque() { return default(byte[]); }
public void SetOpaque(byte[] opaque) { }
}
public sealed partial class RawAcl : System.Security.AccessControl.GenericAcl
{
public RawAcl(byte revision, int capacity) { }
public RawAcl(byte[] binaryForm, int offset) { }
public override int BinaryLength { get { return default(int); } }
public override int Count { get { return default(int); } }
public override System.Security.AccessControl.GenericAce this[int index] { get { return default(System.Security.AccessControl.GenericAce); } set { } }
public override byte Revision { get { return default(byte); } }
public override void GetBinaryForm(byte[] binaryForm, int offset) { }
public void InsertAce(int index, System.Security.AccessControl.GenericAce ace) { }
public void RemoveAce(int index) { }
}
public sealed partial class RawSecurityDescriptor : System.Security.AccessControl.GenericSecurityDescriptor
{
public RawSecurityDescriptor(byte[] binaryForm, int offset) { }
public RawSecurityDescriptor(System.Security.AccessControl.ControlFlags flags, System.Security.Principal.SecurityIdentifier owner, System.Security.Principal.SecurityIdentifier group, System.Security.AccessControl.RawAcl systemAcl, System.Security.AccessControl.RawAcl discretionaryAcl) { }
public RawSecurityDescriptor(string sddlForm) { }
public override System.Security.AccessControl.ControlFlags ControlFlags { get { return default(System.Security.AccessControl.ControlFlags); } }
public System.Security.AccessControl.RawAcl DiscretionaryAcl { get { return default(System.Security.AccessControl.RawAcl); } set { } }
public override System.Security.Principal.SecurityIdentifier Group { get { return default(System.Security.Principal.SecurityIdentifier); } set { } }
public override System.Security.Principal.SecurityIdentifier Owner { get { return default(System.Security.Principal.SecurityIdentifier); } set { } }
public byte ResourceManagerControl { get { return default(byte); } set { } }
public System.Security.AccessControl.RawAcl SystemAcl { get { return default(System.Security.AccessControl.RawAcl); } set { } }
public void SetFlags(System.Security.AccessControl.ControlFlags flags) { }
}
public enum ResourceType
{
DSObject = 8,
DSObjectAll = 9,
FileObject = 1,
KernelObject = 6,
LMShare = 5,
Printer = 3,
ProviderDefined = 10,
RegistryKey = 4,
RegistryWow6432Key = 12,
Service = 2,
Unknown = 0,
WindowObject = 7,
WmiGuidObject = 11,
}
[System.FlagsAttribute]
public enum SecurityInfos
{
DiscretionaryAcl = 4,
Group = 2,
Owner = 1,
SystemAcl = 8,
}
public sealed partial class SystemAcl : System.Security.AccessControl.CommonAcl
{
public SystemAcl(bool isContainer, bool isDS, byte revision, int capacity) { }
public SystemAcl(bool isContainer, bool isDS, int capacity) { }
public SystemAcl(bool isContainer, bool isDS, System.Security.AccessControl.RawAcl rawAcl) { }
public void AddAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void AddAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void AddAudit(System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAuditRule rule) { }
public bool RemoveAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { return default(bool); }
public bool RemoveAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { return default(bool); }
public bool RemoveAudit(System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAuditRule rule) { return default(bool); }
public void RemoveAuditSpecific(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void RemoveAuditSpecific(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void RemoveAuditSpecific(System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAuditRule rule) { }
public void SetAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags) { }
public void SetAudit(System.Security.AccessControl.AuditFlags auditFlags, System.Security.Principal.SecurityIdentifier sid, int accessMask, System.Security.AccessControl.InheritanceFlags inheritanceFlags, System.Security.AccessControl.PropagationFlags propagationFlags, System.Security.AccessControl.ObjectAceFlags objectFlags, System.Guid objectType, System.Guid inheritedObjectType) { }
public void SetAudit(System.Security.Principal.SecurityIdentifier sid, System.Security.AccessControl.ObjectAuditRule rule) { }
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using System.Collections.Generic;
using Microsoft.Win32;
using ESRI.ArcGIS.ADF.BaseClasses;
using ESRI.ArcGIS.ADF.CATIDs;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS;
namespace DynamicObjectTracking
{
/// <summary>
/// A user defined data structure
/// </summary>
public struct NavigationData
{
public double X;
public double Y;
public double Azimuth;
/// <summary>
/// struct constructor
/// </summary>
/// <param name="x">map x coordinate</param>
/// <param name="y">map x coordinate</param>
/// <param name="azimuth">the new map azimuth</param>
public NavigationData(double x, double y, double azimuth)
{
X = x;
Y = y;
Azimuth = azimuth;
}
}
/// <summary>
/// This command triggers the tracking functionality using Dynamic Display
/// </summary>
[Guid("803D4188-AB2F-49f9-9340-42C809887063")]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("DynamicObjectTracking.TrackObject")]
public sealed class TrackObject : BaseCommand
{
#region COM Registration Function(s)
[ComRegisterFunction()]
[ComVisible(false)]
static void RegisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryRegistration(registerType);
//
// TODO: Add any COM registration code here
//
}
[ComUnregisterFunction()]
[ComVisible(false)]
static void UnregisterFunction(Type registerType)
{
// Required for ArcGIS Component Category Registrar support
ArcGISCategoryUnregistration(registerType);
//
// TODO: Add any COM unregistration code here
//
}
#endregion
#region ArcGIS Component Category Registrar generated code
/// <summary>
/// Required method for ArcGIS Component Category registration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryRegistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Register(regKey);
}
/// <summary>
/// Required method for ArcGIS Component Category unregistration -
/// Do not modify the contents of this method with the code editor.
/// </summary>
private static void ArcGISCategoryUnregistration(Type registerType)
{
string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID);
ControlsCommands.Unregister(regKey);
}
#endregion
#region class members
private IHookHelper m_hookHelper = null;
private IDynamicMap m_dynamicMap = null;
private IPoint m_point = null;
private IDynamicGlyph m_VWmarkerGlyph = null;
private IDynamicGlyphFactory2 m_dynamicGlyphFactory = null;
private IDynamicSymbolProperties2 m_dynamicSymbolProps = null;
private bool m_bDrawOnce = true;
private IDisplayTransformation m_displayTransformation = null;
private List<WKSPoint> m_points = null;
private static int m_pointIndex = 0;
private bool m_bIsRunning = false;
private bool m_bOnce = true;
private string m_VWFileName = string.Empty;
private string m_navigationDataFileName = string.Empty;
private NavigationData m_navigationData;
#endregion
/// <summary>
/// class constructor
/// </summary>
public TrackObject()
{
base.m_category = ".NET Samples";
base.m_caption = "Track Dynamic Object";
base.m_message = "Tracking a dynamic object";
base.m_toolTip = "Tracking a dynamic object";
base.m_name = "DotNetSamples.TrackDynamicObject";
try
{
string bitmapResourceName = GetType().Name + ".bmp";
base.m_bitmap = new Bitmap(GetType(), bitmapResourceName);
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap");
}
}
#region Overriden Class Methods
/// <summary>
/// Occurs when this command is created
/// </summary>
/// <param name="hook">Instance of the application</param>
public override void OnCreate(object hook)
{
if (hook == null)
return;
if (m_hookHelper == null)
m_hookHelper = new HookHelperClass();
m_hookHelper.Hook = hook;
m_point = new PointClass();
m_points = new List<WKSPoint>();
}
/// <summary>
/// Occurs when this command is clicked
/// </summary>
public override void OnClick()
{
//make sure to switch into dynamic mode
m_dynamicMap = (IDynamicMap)m_hookHelper.FocusMap;
if (!m_dynamicMap.DynamicMapEnabled)
m_dynamicMap.DynamicMapEnabled = true;
//do initializations
if (m_bOnce)
{
//generate the navigation data
GenerateNavigationData();
m_displayTransformation = m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation;
m_bOnce = false;
}
//hook the dynamic display events
if (!m_bIsRunning)
{
((IDynamicMapEvents_Event)m_dynamicMap).DynamicMapFinished += new IDynamicMapEvents_DynamicMapFinishedEventHandler(OnTimerElapsed);
((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw += new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw);
}
else
{
((IDynamicMapEvents_Event)m_dynamicMap).DynamicMapFinished -= new IDynamicMapEvents_DynamicMapFinishedEventHandler(OnTimerElapsed);
((IDynamicMapEvents_Event)m_dynamicMap).AfterDynamicDraw -= new IDynamicMapEvents_AfterDynamicDrawEventHandler(OnAfterDynamicDraw);
}
//set the running flag
m_bIsRunning = !m_bIsRunning;
}
/// <summary>
/// set the state of the button of the command
/// </summary>
public override bool Checked
{
get
{
return m_bIsRunning;
}
}
#endregion
private void OnTimerElapsed(IDisplay Display, IDynamicDisplay dynamicDisplay)
{
try
{
//make sure that the current tracking point index does not exceed the list index
if (m_pointIndex == (m_points.Count - 1))
{
m_pointIndex = 0;
return;
}
//get the current and the next track location
WKSPoint currentPoint = m_points[m_pointIndex];
WKSPoint nextPoint = m_points[m_pointIndex + 1];
//calculate the azimuth to the next location
double azimuth = (180.0 / Math.PI) * Math.Atan2(nextPoint.X - currentPoint.X, nextPoint.Y - currentPoint.Y);
//set the navigation data structure
m_navigationData.X = currentPoint.X;
m_navigationData.Y = currentPoint.Y;
m_navigationData.Azimuth = azimuth;
//update the map extent and rotation
CenterMap(m_navigationData);
//increment the tracking point index
m_pointIndex++;
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
}
}
private void CenterMap(NavigationData navigationData)
{
try
{
//get the current map visible extent
IEnvelope envelope = m_displayTransformation.VisibleBounds;
if (null == m_point)
{
m_point = new PointClass();
}
//set new map center coordinate
m_point.PutCoords(navigationData.X, navigationData.Y);
//center the map
envelope.CenterAt(m_point);
m_displayTransformation.VisibleBounds = envelope;
//rotate the map to new angle
m_displayTransformation.Rotation = navigationData.Azimuth;
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
}
}
private void GenerateNavigationData()
{
try
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//get navigationData.xml file from DeveloperKit
m_navigationDataFileName = System.IO.Path.Combine(path, @"ArcGIS\data\USAMajorHighways\NavigationData.xml");
if (!System.IO.File.Exists(m_navigationDataFileName))
{
throw new Exception("File " + m_navigationDataFileName + " cannot be found!");
}
XmlTextReader reader = new XmlTextReader(m_navigationDataFileName);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
double X;
double Y;
//get the navigation items
XmlNodeList nodes = doc.DocumentElement.SelectNodes("./navigationItem");
foreach (XmlNode node in nodes)
{
X = Convert.ToDouble(node.Attributes[0].Value);
Y = Convert.ToDouble(node.Attributes[1].Value);
WKSPoint p = new WKSPoint();
p.X = X;
p.Y = Y;
m_points.Add(p);
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine(ex.Message);
}
}
void OnAfterDynamicDraw(esriDynamicMapDrawPhase DynamicMapDrawPhase, IDisplay Display, IDynamicDisplay dynamicDisplay)
{
if (DynamicMapDrawPhase != esriDynamicMapDrawPhase.esriDMDPDynamicLayers)
return;
if (m_bDrawOnce)
{
//cast the DynamicDisplay into DynamicGlyphFactory
m_dynamicGlyphFactory = dynamicDisplay.DynamicGlyphFactory as IDynamicGlyphFactory2;
//cast the DynamicDisplay into DynamicSymbolProperties
m_dynamicSymbolProps = dynamicDisplay as IDynamicSymbolProperties2;
//create the VW dynamic marker glyph from the embedded bitmap resource
Bitmap bitmap = new Bitmap(GetType(), "VW.bmp");
//get bitmap handler
int hBmp = bitmap.GetHbitmap().ToInt32();
//set white transparency color
IColor whiteTransparencyColor = ESRI.ArcGIS.ADF.Connection.Local.Converter.ToRGBColor(Color.FromArgb(0, 0, 0)) as IColor;
//get the VM dynamic marker glyph
m_VWmarkerGlyph = m_dynamicGlyphFactory.CreateDynamicGlyphFromBitmap(esriDynamicGlyphType.esriDGlyphMarker, hBmp, false, whiteTransparencyColor);
m_bDrawOnce = false;
}
//set the symbol alignment so that it will align with towards the symbol heading
m_dynamicSymbolProps.set_RotationAlignment(esriDynamicSymbolType.esriDSymbolMarker, esriDynamicSymbolRotationAlignment.esriDSRANorth);
//set the symbol's properties
m_dynamicSymbolProps.set_DynamicGlyph(esriDynamicSymbolType.esriDSymbolMarker, m_VWmarkerGlyph);
m_dynamicSymbolProps.SetScale(esriDynamicSymbolType.esriDSymbolMarker, 1.3f, 1.3f);
m_dynamicSymbolProps.SetColor(esriDynamicSymbolType.esriDSymbolMarker, 1.0f, 1.0f, 0.0f, 1.0f); // yellow
//set the heading of the current symbol
m_dynamicSymbolProps.set_Heading(esriDynamicSymbolType.esriDSymbolMarker, (float)m_navigationData.Azimuth);
//draw the current location
dynamicDisplay.DrawMarker(m_point);
}
}
}
| |
using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
//@@@
public static partial class Symbol
{
/// <summary>
/// @@TOTAL_WRITE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-transact-sql
/// </summary>
/// <returns></returns>
[ClauseStyleConverter(Name = "@@ERROR")]
public static int AtAtError() => throw new InvalitContextException(nameof(AtAtError));
/// <summary>
/// @@IDENTITY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/identity-transact-sql
/// </summary>
/// <returns></returns>
[ClauseStyleConverter(Name = "@@IDENTITY")]
public static decimal AtAtIdentity() => throw new InvalitContextException(nameof(AtAtIdentity));
/// <summary>
/// @@PACK_RECEIVED
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/pack-received-transact-sql
/// </summary>
/// <returns></returns>
[ClauseStyleConverter(Name = "@@PACK_RECEIVED")]
public static int AtAtPackReceived() => throw new InvalitContextException(nameof(AtAtPackReceived));
/// <summary>
/// @@ROWCOUNT
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/rowcount-transact-sql
/// </summary>
/// <returns></returns>
[ClauseStyleConverter(Name = "@@ROWCOUNT")]
public static int AtAtRowCount() => throw new InvalitContextException(nameof(AtAtRowCount));
/// <summary>
/// @@TRANCOUNT
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/trancount-transact-sql
/// </summary>
/// <returns></returns>
[ClauseStyleConverter(Name = "@@TRANCOUNT")]
public static int AtAtTranCount() => throw new InvalitContextException(nameof(AtAtError));
/// <summary>
/// BINARY_CHECKSUM
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/binary-checksum-transact-sql
/// </summary>
/// <param name="expression">columns or Asterisk()</param>
/// <returns>check sum.</returns>
[FuncStyleConverter]
public static int Binary_CheckSum(params object[] expression) => throw new InvalitContextException(nameof(Binary_CheckSum));
/// <summary>
/// CHECKSUM
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/checksum-transact-sql
/// </summary>
/// <param name="expression">columns or Asterisk()</param>
/// <returns>check sum.</returns>
[FuncStyleConverter]
public static int CheckSum(params object[] expression) => throw new InvalitContextException(nameof(CheckSum));
/// <summary>
/// COMPRESS
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/compress-transact-sql
/// </summary>
/// <param name="expression">columns or Asterisk()</param>
/// <returns>Compressed value.</returns>
[FuncStyleConverter]
public static byte[] Compress(object expression) => throw new InvalitContextException(nameof(Compress));
/// <summary>
/// CONNECTIONPROPERTY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/connectionproperty-transact-sql
/// </summary>
/// <param name="property">columns or Asterisk()</param>
/// <returns>Connection property.</returns>
[FuncStyleConverter]
public static object ConnectionProperty(object property) => throw new InvalitContextException(nameof(ConnectionProperty));
/// <summary>
/// CONTEXT_INFO
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/context-info-transact-sql
/// </summary>
/// <returns>context_info.</returns>
[FuncStyleConverter]
public static byte[] Context_Info() => throw new InvalitContextException(nameof(Context_Info));
/// <summary>
/// CURRENT_REQUEST_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/current-request-id-transact-sql
/// </summary>
/// <returns>To find exact information about the current session and current request, use @@SPID and CURRENT_REQUEST_ID(), respectively.</returns>
[FuncStyleConverter]
public static short Current_Request_Id() => throw new InvalitContextException(nameof(Current_Request_Id));
/// <summary>
/// CURRENT_TRANSACTION_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/current-transaction-id-transact-sql
/// </summary>
/// <returns>Transaction ID of the current transaction in the current session, taken from sys.dm_tran_current_transaction (Transact-SQL).</returns>
[FuncStyleConverter]
public static long Current_Transaction_Id() => throw new InvalitContextException(nameof(Current_Transaction_Id));
/// <summary>
/// DECOMPRESS
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/decompress-transact-sql
/// </summary>
/// <param name="expression">compressed value.</param>
/// <returns>decompressed value.</returns>
[FuncStyleConverter]
public static byte[] Decompress(byte[] expression) => throw new InvalitContextException(nameof(Decompress));
/// <summary>
/// ERROR_LINE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-line-transact-sql
/// </summary>
/// <returns>error line.</returns>
[FuncStyleConverter]
public static int Error_Line() => throw new InvalitContextException(nameof(Error_Line));
/// <summary>
/// ERROR_MESSAGE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-message-transact-sql
/// </summary>
/// <returns>error message.</returns>
[FuncStyleConverter]
public static int Error_Message() => throw new InvalitContextException(nameof(Error_Message));
/// <summary>
/// ERROR_NUMBER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-number-transact-sql
/// </summary>
/// <returns>error number.</returns>
[FuncStyleConverter]
public static int Error_Number() => throw new InvalitContextException(nameof(Error_Number));
/// <summary>
/// ERROR_PROCEDURE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-procedure-transact-sql
/// </summary>
/// <returns>error procedure.</returns>
[FuncStyleConverter]
public static int Error_Procedure() => throw new InvalitContextException(nameof(Error_Procedure));
/// <summary>
/// ERROR_SEVERITY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-severity-transact-sql
/// </summary>
/// <returns>error severity.</returns>
[FuncStyleConverter]
public static int Error_Severity() => throw new InvalitContextException(nameof(Error_Severity));
/// <summary>
/// ERROR_STATE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/error-state-transact-sql
/// </summary>
/// <returns>error .</returns>
[FuncStyleConverter]
public static int Error_State() => throw new InvalitContextException(nameof(Error_State));
/// <summary>
/// FORMATMESSAGE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/formatmessage-transact-sql
/// </summary>
/// <param name="msg">msg.</param>
/// <param name="param_values">param_values.</param>
/// <returns>formated message.</returns>
[FuncStyleConverter]
public static string FormatMessage(object msg, params object[] param_values) => throw new InvalitContextException(nameof(FormatMessage));
/// <summary>
/// GET_FILESTREAM_TRANSACTION_CONTEXT
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/get-filestream-transaction-context-transact-sql
/// </summary>
/// <returns>token.</returns>
[FuncStyleConverter]
public static object Get_FileStream_Transaction_Context() => throw new InvalitContextException(nameof(Get_FileStream_Transaction_Context));
/// <summary>
/// GETANSINULL
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/getansinull-transact-sql
/// </summary>
/// <param name="database">database.</param>
/// <returns>Returns the default nullability for the database for this session.</returns>
[FuncStyleConverter]
public static int GetAnsiNull(string database) => throw new InvalitContextException(nameof(GetAnsiNull));
/// <summary>
/// HOST_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/host-id-transact-sql
/// </summary>
/// <returns>host id.</returns>
[FuncStyleConverter]
public static string Host_Id() => throw new InvalitContextException(nameof(Host_Id));
/// <summary>
/// HOST_NAME
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/host-name-transact-sql
/// </summary>
/// <returns>host name.</returns>
[FuncStyleConverter]
public static string Host_Name() => throw new InvalitContextException(nameof(Host_Name));
/// <summary>
/// Replaces NULL with the specified replacement value.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql
/// </summary>
/// <param name="check_expression"></param>
/// <param name="replacement_value"></param>
/// <returns>check_expression or replacement_value.</returns>
[FuncStyleConverter]
public static object IsNull(object check_expression, object replacement_value) => throw new InvalitContextException(nameof(IsNull));
/// <summary>
/// ISNUMERIC
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/isnumeric-transact-sql
/// </summary>
/// <param name="expression"></param>
/// <returns>is numeric expression.</returns>
[FuncStyleConverter]
public static int IsNumeric(object expression) => throw new InvalitContextException(nameof(IsNumeric));
/// <summary>
/// MIN_ACTIVE_ROWVERSION
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/min-active-rowversion-transact-sql
/// </summary>
/// <returns></returns>
[FuncStyleConverter]
public static object Min_Active_Rowversion() => throw new InvalitContextException(nameof(Min_Active_Rowversion));
/// <summary>
/// NEWID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
/// </summary>
/// <returns>new id.</returns>
[FuncStyleConverter]
public static object NewId() => throw new InvalitContextException(nameof(NewId));
/// <summary>
/// NEWSEQUENTIALID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/newsequentialid-transact-sql
/// </summary>
/// <returns>new sequential id.</returns>
[FuncStyleConverter]
public static object NewSequentialdId() => throw new InvalitContextException(nameof(NewSequentialdId));
/// <summary>
/// ROWCOUNT_BIG
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/rowcount-big-transact-sql
/// </summary>
/// <returns>row count.</returns>
[FuncStyleConverter]
public static long RowCount_Big() => throw new InvalitContextException(nameof(RowCount_Big));
/// <summary>
/// SESSION_CONTEXT
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/session-context-transact-sql
/// </summary>
/// <param name="key">key.</param>
/// <returns>session context.</returns>
[FuncStyleConverter]
public static object Session_Context(string key) => throw new InvalitContextException(nameof(Session_Context));
/// <summary>
/// SESSION_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/session-id-transact-sql
/// </summary>
/// <returns>sesson id.</returns>
[FuncStyleConverter]
public static string Session_Id() => throw new InvalitContextException(nameof(Session_Id));
/// <summary>
/// XACT_STATE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/xact-state-transact-sql
/// </summary>
/// <returns>transaction state of a current running request. </returns>
[FuncStyleConverter]
public static short Xact_State() => throw new InvalitContextException(nameof(Xact_State));
//TODO ????
/*
$PARTITION
*/
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
using osu.Framework.Extensions;
using osu.Framework.Graphics;
using osu.Framework.Screens;
using osu.Framework.Utils;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Database;
using osu.Game.IO.Archives;
using osu.Game.Overlays;
using osu.Game.Overlays.Notifications;
using osu.Game.Rulesets;
using osu.Game.Screens.Backgrounds;
using osuTK;
using osuTK.Graphics;
using Realms;
namespace osu.Game.Screens.Menu
{
public abstract class IntroScreen : StartupScreen
{
/// <summary>
/// Whether we have loaded the menu previously.
/// </summary>
public bool DidLoadMenu { get; private set; }
/// <summary>
/// A hash used to find the associated beatmap if already imported.
/// </summary>
protected abstract string BeatmapHash { get; }
/// <summary>
/// A source file to use as an import source if the intro beatmap is not yet present.
/// Should be within the "Tracks" namespace of game resources.
/// </summary>
protected abstract string BeatmapFile { get; }
protected IBindable<bool> MenuVoice { get; private set; }
protected IBindable<bool> MenuMusic { get; private set; }
private WorkingBeatmap initialBeatmap;
protected ITrack Track { get; private set; }
private const int exit_delay = 3000;
private Sample seeya;
protected virtual string SeeyaSampleName => "Intro/seeya";
private LeasedBindable<WorkingBeatmap> beatmap;
private OsuScreen nextScreen;
[Resolved]
private AudioManager audio { get; set; }
[Resolved]
private MusicController musicController { get; set; }
[CanBeNull]
private readonly Func<OsuScreen> createNextScreen;
[Resolved]
private RulesetStore rulesets { get; set; }
/// <summary>
/// Whether the <see cref="Track"/> is provided by osu! resources, rather than a user beatmap.
/// Only valid during or after <see cref="LogoArriving"/>.
/// </summary>
protected bool UsingThemedIntro { get; private set; }
protected IntroScreen([CanBeNull] Func<MainMenu> createNextScreen = null)
{
this.createNextScreen = createNextScreen;
}
[Resolved]
private BeatmapManager beatmaps { get; set; }
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, Framework.Game game, RealmAccess realm)
{
// prevent user from changing beatmap while the intro is still running.
beatmap = Beatmap.BeginLease(false);
MenuVoice = config.GetBindable<bool>(OsuSetting.MenuVoice);
MenuMusic = config.GetBindable<bool>(OsuSetting.MenuMusic);
seeya = audio.Samples.Get(SeeyaSampleName);
// if the user has requested not to play theme music, we should attempt to find a random beatmap from their collection.
if (!MenuMusic.Value)
{
realm.Run(r =>
{
var usableBeatmapSets = r.All<BeatmapSetInfo>().Where(s => !s.DeletePending && !s.Protected).AsRealmCollection();
int setCount = usableBeatmapSets.Count;
if (setCount > 0)
{
var found = usableBeatmapSets[RNG.Next(0, setCount - 1)].Beatmaps.FirstOrDefault();
if (found != null)
initialBeatmap = beatmaps.GetWorkingBeatmap(found);
}
});
}
// we generally want a song to be playing on startup, so use the intro music even if a user has specified not to if no other track is available.
if (initialBeatmap == null)
{
// Intro beatmaps are generally made using the osu! ruleset.
// It might not be present in test projects for other rulesets.
bool osuRulesetPresent = rulesets.GetRuleset(0) != null;
if (!loadThemedIntro() && osuRulesetPresent)
{
// if we detect that the theme track or beatmap is unavailable this is either first startup or things are in a bad state.
// this could happen if a user has nuked their files store. for now, reimport to repair this.
var import = beatmaps.Import(new ZipArchiveReader(game.Resources.GetStream($"Tracks/{BeatmapFile}"), BeatmapFile)).GetResultSafely();
import?.PerformWrite(b => b.Protected = true);
loadThemedIntro();
}
}
bool loadThemedIntro()
{
var setInfo = beatmaps.QueryBeatmapSet(b => b.Hash == BeatmapHash);
if (setInfo == null)
return false;
setInfo.PerformRead(s =>
{
if (s.Beatmaps.Count == 0)
return;
initialBeatmap = beatmaps.GetWorkingBeatmap(s.Beatmaps.First());
});
return UsingThemedIntro = initialBeatmap != null;
}
}
public override void OnEntering(IScreen last)
{
base.OnEntering(last);
ensureEventuallyArrivingAtMenu();
}
[Resolved]
private NotificationOverlay notifications { get; set; }
private void ensureEventuallyArrivingAtMenu()
{
// This intends to handle the case where an intro may get stuck.
// Historically, this could happen if the host system's audio device is in a state it can't
// play audio, causing a clock to never elapse time and the intro to never end.
//
// This safety measure gives the user a chance to fix the problem from the settings menu.
Scheduler.AddDelayed(() =>
{
if (DidLoadMenu)
return;
PrepareMenuLoad();
LoadMenu();
notifications.Post(new SimpleErrorNotification
{
Text = "osu! doesn't seem to be able to play audio correctly.\n\nPlease try changing your audio device to a working setting."
});
}, 5000);
}
public override void OnResuming(IScreen last)
{
this.FadeIn(300);
double fadeOutTime = exit_delay;
var track = musicController.CurrentTrack;
// ensure the track doesn't change or loop as we are exiting.
track.Looping = false;
Beatmap.Disabled = true;
// we also handle the exit transition.
if (MenuVoice.Value)
{
seeya.Play();
// if playing the outro voice, we have more time to have fun with the background track.
// initially fade to almost silent then ramp out over the remaining time.
const double initial_fade = 200;
track
.VolumeTo(0.03f, initial_fade).Then()
.VolumeTo(0, fadeOutTime - initial_fade, Easing.In);
}
else
{
fadeOutTime = 500;
// if outro voice is turned off, just do a simple fade out.
track.VolumeTo(0, fadeOutTime, Easing.Out);
}
//don't want to fade out completely else we will stop running updates.
Game.FadeTo(0.01f, fadeOutTime).OnComplete(_ => this.Exit());
base.OnResuming(last);
}
public override void OnSuspending(IScreen next)
{
base.OnSuspending(next);
initialBeatmap = null;
}
protected override BackgroundScreen CreateBackground() => new BackgroundScreenBlack();
protected virtual void StartTrack()
{
// Only start the current track if it is the menu music. A beatmap's track is started when entering the Main Menu.
if (UsingThemedIntro)
Track.Start();
}
protected override void LogoArriving(OsuLogo logo, bool resuming)
{
base.LogoArriving(logo, resuming);
logo.Colour = Color4.White;
logo.Triangles = false;
logo.Ripple = false;
if (!resuming)
{
// generally this can never be null
// an exception is running ruleset tests, where the osu! ruleset may not be present (causing importing the intro to fail).
if (initialBeatmap != null)
beatmap.Value = initialBeatmap;
Track = beatmap.Value.Track;
// ensure the track starts at maximum volume
musicController.CurrentTrack.FinishTransforms();
logo.MoveTo(new Vector2(0.5f));
logo.ScaleTo(Vector2.One);
logo.Hide();
}
else
{
const int quick_appear = 350;
int initialMovementTime = logo.Alpha > 0.2f ? quick_appear : 0;
logo.MoveTo(new Vector2(0.5f), initialMovementTime, Easing.OutQuint);
logo
.ScaleTo(1, initialMovementTime, Easing.OutQuint)
.FadeIn(quick_appear, Easing.OutQuint)
.Then()
.RotateTo(20, exit_delay * 1.5f)
.FadeOut(exit_delay);
}
}
protected void PrepareMenuLoad()
{
if (nextScreen != null)
return;
nextScreen = createNextScreen?.Invoke();
if (nextScreen != null)
LoadComponentAsync(nextScreen);
}
protected void LoadMenu()
{
if (DidLoadMenu)
return;
beatmap.Return();
DidLoadMenu = true;
if (nextScreen != null)
this.Push(nextScreen);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.AspNet.Authentication;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Mvc.Rendering;
using AspNetBootstrapLess;
using AspNetBootstrapLess.Models;
namespace AspNetBootstrapLess.Controllers
{
[Authorize]
public class AccountController : Controller
{
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
UserManager = userManager;
SignInManager = signInManager;
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public SignInManager<ApplicationUser> SignInManager { get; private set; }
// GET: /Account/Login
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
{
ViewBag.ReturnUrl = returnUrl;
if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Invalid login attempt.");
return View(model);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/Register
[AllowAnonymous]
[HttpGet]
public IActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
//var code = await UserManager.GenerateEmailConfirmationTokenAsync(user);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
//await MessageServices.SendEmailAsync(model.Email, "Confirm your account",
// "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LogOff()
{
SignInManager.SignOut();
return RedirectToAction("Index", "Home");
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
// Request a redirect to the external login provider.
var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
var properties = SignInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
return new ChallengeResult(provider, properties);
}
//
// GET: /Account/ExternalLoginCallback
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
var info = await SignInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login.
var result = await SignInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
if (result.Succeeded)
{
return RedirectToLocal(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl });
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
// If the user does not have an account, then ask the user to create an account.
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = info.LoginProvider;
var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email);
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
{
if (User.IsSignedIn())
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await SignInManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user, info);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
// GET: /Account/ConfirmEmail
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var user = await UserManager.FindByIdAsync(userId);
if (user == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(user, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
// Send an email with this link
// var code = await UserManager.GeneratePasswordResetTokenAsync(user);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Context.Request.Scheme);
// await MessageServices.SendEmailAsync(model.Email, "Reset Password",
// "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
// return View("ForgotPasswordConfirmation");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPassword(string code = null)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[HttpGet]
[AllowAnonymous]
public IActionResult ResetPasswordConfirmation()
{
return View();
}
//
// GET: /Account/SendCode
[HttpGet]
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false)
{
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(user);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
// Generate the token and send it
var code = await UserManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider);
if (string.IsNullOrWhiteSpace(code))
{
return View("Error");
}
var message = "Your security code is: " + code;
if (model.SelectedProvider == "Email")
{
await MessageServices.SendEmailAsync(await UserManager.GetEmailAsync(user), "Security Code", message);
}
else if (model.SelectedProvider == "Phone")
{
await MessageServices.SendSmsAsync(await UserManager.GetPhoneNumberAsync(user), message);
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/VerifyCode
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null)
{
// Require that the user has already logged in via username/password or external login
var user = await SignInManager.GetTwoFactorAuthenticationUserAsync();
if (user == null)
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser);
if (result.Succeeded)
{
return RedirectToLocal(model.ReturnUrl);
}
if (result.IsLockedOut)
{
return View("Lockout");
}
else
{
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
#region Helpers
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
private async Task<ApplicationUser> GetCurrentUserAsync()
{
return await UserManager.FindByIdAsync(Context.User.GetUserId());
}
private IActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
// todo: dependency on runtime (due to logging)
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
namespace Orleans.Threading
{
/// <summary>
/// Essentially FixedThreadPool with work stealing
/// </summary>
internal class ThreadPoolExecutor : IExecutor, IHealthCheckable
{
private readonly ThreadPoolWorkQueue workQueue;
private readonly ThreadPoolExecutorOptions options;
private readonly SchedulerStatisticsGroup schedulerStatistics;
private readonly StageAnalysisStatisticsGroup schedulerStageStatistics;
private readonly IOptions<StatisticsOptions> statisticsOptions;
private readonly ThreadPoolTrackingStatistic statistic;
private readonly ExecutingWorkItemsTracker executingWorkTracker;
private readonly ILogger log;
public ThreadPoolExecutor(
ThreadPoolExecutorOptions options,
SchedulerStatisticsGroup schedulerStatistics,
StageAnalysisStatisticsGroup schedulerStageStatistics,
IOptions<StatisticsOptions> statisticsOptions)
{
this.options = options ?? throw new ArgumentNullException(nameof(options));
this.schedulerStatistics = schedulerStatistics;
this.schedulerStageStatistics = schedulerStageStatistics;
this.statisticsOptions = statisticsOptions;
this.workQueue = new ThreadPoolWorkQueue();
this.statistic = new ThreadPoolTrackingStatistic(options.Name, options.LoggerFactory, statisticsOptions, schedulerStageStatistics);
this.log = options.LoggerFactory.CreateLogger<ThreadPoolExecutor>();
this.executingWorkTracker = new ExecutingWorkItemsTracker(options, this.log);
options.CancellationTokenSource.Token.Register(Complete);
for (var threadIndex = 0; threadIndex < options.DegreeOfParallelism; threadIndex++)
{
RunWorker(threadIndex);
}
}
public void QueueWorkItem(WaitCallback callback, object state = null)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
var workItem = new WorkItem(callback, state, options.WorkItemExecutionTimeTreshold, options.WorkItemStatusProvider);
statistic.OnEnQueueRequest(workItem);
workQueue.Enqueue(workItem, forceGlobal: false);
}
public bool CheckHealth(DateTime lastCheckTime)
{
return !executingWorkTracker.HasFrozenWork();
}
public void Complete()
{
workQueue.CompleteAdding();
}
private void ProcessWorkItems(ExecutionContext context)
{
var threadLocals = workQueue.EnsureCurrentThreadHasQueue();
statistic.OnStartExecution();
try
{
while (!ShouldStop())
{
while (workQueue.TryDequeue(threadLocals, out var workItem))
{
if (ShouldStop())
{
break;
}
context.ExecuteWithFilters(workItem);
}
workQueue.WaitForWork();
}
if (options.DrainAfterCancel)
{
// Give a chance to drain all pending items fast
while (workQueue.TryDequeue(threadLocals, out var workItem))
{
context.ExecuteWithFilters(workItem);
}
}
}
catch (Exception ex)
{
if (ex is ThreadAbortException)
{
return;
}
log.Error(ErrorCode.ExecutorProcessingError, string.Format(SR.Executor_On_Exception, options.Name), ex);
}
finally
{
statistic.OnStopExecution();
}
bool ShouldStop()
{
return context.CancellationTokenSource.IsCancellationRequested;
}
}
private void RunWorker(int index)
{
var actionFilters = new ActionFilter<ExecutionContext>[]
{
new StatisticsTracker(statistic, options.DelayWarningThreshold, log, this.schedulerStatistics),
executingWorkTracker
}.Union(options.ExecutionFilters);
var exceptionFilters = new[] { new ThreadAbortHandler(log) }.Union(options.ExceptionFilters);
var context = new ExecutionContext(
actionFilters,
exceptionFilters,
options.CancellationTokenSource,
index);
new ThreadPoolThread(
options.Name + index,
options.CancellationTokenSource.Token,
options.LoggerFactory,
this.statisticsOptions,
this.schedulerStageStatistics)
.QueueWorkItem(_ => ProcessWorkItems(context));
}
private sealed class ThreadAbortHandler : ExecutionExceptionFilter
{
private readonly ILogger log;
public ThreadAbortHandler(ILogger log)
{
this.log = log;
}
public override bool ExceptionHandler(Exception ex, ExecutionContext context)
{
if (!(ex is ThreadAbortException))
{
return false;
}
if (log.IsEnabled(LogLevel.Debug)) log.Debug(SR.On_Thread_Abort_Exit, ex);
Thread.ResetAbort();
context.CancellationTokenSource.Cancel();
return true;
}
}
private sealed class StatisticsTracker : ExecutionActionFilter
{
private readonly ThreadPoolTrackingStatistic statistic;
private readonly TimeSpan delayWarningThreshold;
private readonly ILogger log;
private readonly SchedulerStatisticsGroup schedulerStatistics;
public StatisticsTracker(ThreadPoolTrackingStatistic statistic, TimeSpan delayWarningThreshold, ILogger log, SchedulerStatisticsGroup schedulerStatistics)
{
this.statistic = statistic;
this.delayWarningThreshold = delayWarningThreshold;
this.log = log;
this.schedulerStatistics = schedulerStatistics;
}
public override void OnActionExecuting(ExecutionContext context)
{
TrackRequestDequeue(context.WorkItem);
statistic.OnStartProcessing();
}
public override void OnActionExecuted(ExecutionContext context)
{
statistic.OnStopProcessing();
statistic.IncrementNumberOfProcessed();
}
private void TrackRequestDequeue(WorkItem workItem)
{
var waitTime = workItem.TimeSinceQueued;
if (waitTime > delayWarningThreshold && !System.Diagnostics.Debugger.IsAttached && workItem.State != null)
{
this.schedulerStatistics.NumLongQueueWaitTimes.Increment();
log.Warn(ErrorCode.SchedulerWorkerPoolThreadQueueWaitTime, SR.Queue_Item_WaitTime, waitTime, workItem.State);
}
statistic.OnDeQueueRequest(workItem);
}
}
private sealed class ExecutingWorkItemsTracker : ExecutionActionFilter
{
private readonly WorkItem[] runningItems;
private readonly ILogger log;
public ExecutingWorkItemsTracker(ThreadPoolExecutorOptions options, ILogger log)
{
if (options == null) throw new ArgumentNullException(nameof(options));
this.runningItems = new WorkItem[GetThreadSlot(options.DegreeOfParallelism)];
this.log = log ?? throw new ArgumentNullException(nameof(log));
}
public override void OnActionExecuting(ExecutionContext context)
{
runningItems[GetThreadSlot(context.ThreadIndex)] = context.WorkItem;
}
public override void OnActionExecuted(ExecutionContext context)
{
runningItems[GetThreadSlot(context.ThreadIndex)] = null;
}
public bool HasFrozenWork()
{
var frozen = false;
foreach (var workItem in runningItems)
{
if (workItem != null && workItem.IsFrozen())
{
frozen = true;
this.log.Error(
ErrorCode.ExecutorTurnTooLong,
string.Format(SR.WorkItem_LongExecutionTime, workItem.GetWorkItemStatus(true)));
}
}
return frozen;
}
private static int GetThreadSlot(int threadIndex)
{
// false sharing prevention
const int cacheLineSize = 64;
const int padding = cacheLineSize;
return threadIndex * padding;
}
}
internal static class SR
{
public const string WorkItem_ExecutionTime = "WorkItem={0} Executing for {1} {2}";
public const string WorkItem_LongExecutionTime = "Work item {0} has been executing for long time.";
public const string Queue_Item_WaitTime = "Queue wait time of {0} for Item {1}";
public const string On_Thread_Abort_Exit = "Received thread abort exception - exiting. {0}.";
public const string Executor_On_Exception = "Executor {0} caught an exception.";
}
}
internal interface IExecutable
{
void Execute();
}
internal class WorkItem : IExecutable
{
public static WorkItem NoOp = new WorkItem(s => { }, null, TimeSpan.MaxValue);
private readonly WaitCallback callback;
private readonly StatusProvider statusProvider;
private readonly TimeSpan executionTimeTreshold;
private readonly DateTime enqueueTime;
private ITimeInterval executionTime;
public WorkItem(
WaitCallback callback,
object state,
TimeSpan executionTimeTreshold,
StatusProvider statusProvider = null)
{
this.callback = callback;
this.State = state;
this.executionTimeTreshold = executionTimeTreshold;
this.statusProvider = statusProvider ?? NoOpStatusProvider;
this.enqueueTime = DateTime.UtcNow;
}
// Being tracked only when queue tracking statistic is enabled. Todo: remove implicit behavior?
internal ITimeInterval ExecutionTime
{
get
{
EnsureExecutionTime();
return executionTime;
}
}
// for lightweight execution time tracking
public DateTime ExecutionStart { get; private set; }
internal TimeSpan TimeSinceQueued => Utils.Since(enqueueTime);
internal object State { get; }
public void Execute()
{
ExecutionStart = DateTime.UtcNow;
callback.Invoke(State);
}
public void EnsureExecutionTime()
{
if (executionTime == null)
{
executionTime = TimeIntervalFactory.CreateTimeInterval(true);
}
}
internal string GetWorkItemStatus(bool detailed)
{
return string.Format(
ThreadPoolExecutor.SR.WorkItem_ExecutionTime, State, Utils.Since(ExecutionStart),
statusProvider?.Invoke(State, detailed));
}
internal bool IsFrozen()
{
return Utils.Since(ExecutionStart) > executionTimeTreshold;
}
internal delegate string StatusProvider(object state, bool detailed);
private static readonly StatusProvider NoOpStatusProvider = (s, d) => string.Empty;
}
internal class ExecutionContext : IExecutable
{
private readonly FiltersApplicant<ExecutionContext> filtersApplicant;
public ExecutionContext(
IEnumerable<ActionFilter<ExecutionContext>> actionFilters,
IEnumerable<ExceptionFilter<ExecutionContext>> exceptionFilters,
CancellationTokenSource cts,
int threadIndex)
{
filtersApplicant = new FiltersApplicant<ExecutionContext>(actionFilters, exceptionFilters);
CancellationTokenSource = cts;
ThreadIndex = threadIndex;
}
public CancellationTokenSource CancellationTokenSource { get; }
public WorkItem WorkItem { get; private set; }
internal int ThreadIndex { get; }
public void ExecuteWithFilters(WorkItem workItem)
{
WorkItem = workItem;
try
{
filtersApplicant.Apply(this);
}
finally
{
Reset();
}
}
public void Execute()
{
WorkItem.Execute();
}
private void Reset()
{
WorkItem = null;
}
}
internal class ThreadPoolTrackingStatistic
{
private readonly ThreadTrackingStatistic threadTracking;
private readonly QueueTrackingStatistic queueTracking;
private readonly StatisticsLevel statisticsLevel;
public ThreadPoolTrackingStatistic(string name, ILoggerFactory loggerFactory, IOptions<StatisticsOptions> statisticsOptions, StageAnalysisStatisticsGroup schedulerStageStatistics)
{
this.statisticsLevel = statisticsOptions.Value.CollectionLevel;
if (statisticsLevel.CollectQueueStats())
{
queueTracking = new QueueTrackingStatistic(name, statisticsOptions);
}
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
threadTracking = new ThreadTrackingStatistic(name, loggerFactory, statisticsOptions, schedulerStageStatistics);
}
}
public void OnStartExecution()
{
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
queueTracking.OnStartExecution();
}
}
public void OnDeQueueRequest(WorkItem workItem)
{
if (this.statisticsLevel.CollectDetailedQueueStatistics())
{
queueTracking.OnDeQueueRequest(workItem.ExecutionTime);
}
}
public void OnEnQueueRequest(WorkItem workItem)
{
if (this.statisticsLevel.CollectDetailedQueueStatistics())
{
queueTracking.OnEnQueueRequest(1, queueLength: 0, itemInQueue: workItem.ExecutionTime);
}
}
public void OnStartProcessing()
{
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
threadTracking.OnStartProcessing();
}
}
internal void OnStopProcessing()
{
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
threadTracking.OnStopProcessing();
}
}
internal void IncrementNumberOfProcessed()
{
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
threadTracking.IncrementNumberOfProcessed();
}
}
public void OnStopExecution()
{
if (this.statisticsLevel.CollectDetailedThreadStatistics())
{
threadTracking.OnStopExecution();
}
}
}
}
| |
// 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics;
namespace System.Reflection.Emit
{
internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo
{
#region Private Static Members
internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type)
{
return new MethodOnTypeBuilderInstantiation(method, type);
}
#endregion
#region Private Data Members
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type)
{
Debug.Assert(method is MethodBuilder || method is RuntimeMethodInfo);
m_method = method;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_method.GetParameterTypes();
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_method.MemberType; } }
public override String Name { get { return m_method.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); }
public override Module Module { get { return m_method.Module; } }
#endregion
#region MethodBase Members
public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_method.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_method.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_method.CallingConvention; } }
public override Type[] GetGenericArguments() { return m_method.GetGenericArguments(); }
public override MethodInfo GetGenericMethodDefinition() { return m_method; }
public override bool IsGenericMethodDefinition { get { return m_method.IsGenericMethodDefinition; } }
public override bool ContainsGenericParameters { get { return m_method.ContainsGenericParameters; } }
public override MethodInfo MakeGenericMethod(params Type[] typeArgs)
{
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(SR.Arg_NotGenericMethodDefinition);
return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs);
}
public override bool IsGenericMethod { get { return m_method.IsGenericMethod; } }
#endregion
#region Public Abstract\Virtual Members
public override Type ReturnType { get { return m_method.ReturnType; } }
public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } }
public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } }
public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); }
#endregion
}
internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo
{
#region Private Static Members
internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type)
{
return new ConstructorOnTypeBuilderInstantiation(Constructor, type);
}
#endregion
#region Private Data Members
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type)
{
Debug.Assert(constructor is ConstructorBuilder || constructor is RuntimeConstructorInfo);
m_ctor = constructor;
m_type = type;
}
#endregion
internal override Type[] GetParameterTypes()
{
return m_ctor.GetParameterTypes();
}
internal override Type GetReturnType()
{
return DeclaringType;
}
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return m_ctor.MemberType; } }
public override String Name { get { return m_ctor.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
ConstructorBuilder cb = m_ctor as ConstructorBuilder;
if (cb != null)
return cb.MetadataTokenInternal;
else
{
Debug.Assert(m_ctor is RuntimeConstructorInfo);
return m_ctor.MetadataToken;
}
}
}
public override Module Module { get { return m_ctor.Module; } }
#endregion
#region MethodBase Members
public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); }
public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); }
public override RuntimeMethodHandle MethodHandle { get { return m_ctor.MethodHandle; } }
public override MethodAttributes Attributes { get { return m_ctor.Attributes; } }
public override Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new NotSupportedException();
}
public override CallingConventions CallingConvention { get { return m_ctor.CallingConvention; } }
public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); }
public override bool IsGenericMethodDefinition { get { return false; } }
public override bool ContainsGenericParameters { get { return false; } }
public override bool IsGenericMethod { get { return false; } }
#endregion
#region ConstructorInfo Members
public override Object Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
{
throw new InvalidOperationException();
}
#endregion
}
internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo
{
#region Private Static Members
internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type)
{
FieldInfo m = null;
// This ifdef was introduced when non-generic collections were pulled from
// silverlight. See code:Dictionary#DictionaryVersusHashtableThreadSafety
// for information about this change.
//
// There is a pre-existing race condition in this code with the side effect
// that the second thread's value clobbers the first in the hashtable. This is
// an acceptable race condition since we make no guarantees that this will return the
// same object.
//
// We're not entirely sure if this cache helps any specific scenarios, so
// long-term, one could investigate whether it's needed. In any case, this
// method isn't expected to be on any critical paths for performance.
if (type.m_hashtable.Contains(Field))
{
m = type.m_hashtable[Field] as FieldInfo;
}
else
{
m = new FieldOnTypeBuilderInstantiation(Field, type);
type.m_hashtable[Field] = m;
}
return m;
}
#endregion
#region Private Data Members
private FieldInfo m_field;
private TypeBuilderInstantiation m_type;
#endregion
#region Constructor
internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type)
{
Debug.Assert(field is FieldBuilder || field is RuntimeFieldInfo);
m_field = field;
m_type = type;
}
#endregion
internal FieldInfo FieldInfo { get { return m_field; } }
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } }
public override String Name { get { return m_field.Name; } }
public override Type DeclaringType { get { return m_type; } }
public override Type ReflectedType { get { return m_type; } }
public override Object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); }
public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); }
internal int MetadataTokenInternal
{
get
{
FieldBuilder fb = m_field as FieldBuilder;
if (fb != null)
return fb.MetadataTokenInternal;
else
{
Debug.Assert(m_field is RuntimeFieldInfo);
return m_field.MetadataToken;
}
}
}
public override Module Module { get { return m_field.Module; } }
#endregion
#region Public Abstract\Virtual Members
public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); }
public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); }
public override void SetValueDirect(TypedReference obj, Object value)
{
throw new NotImplementedException();
}
public override Object GetValueDirect(TypedReference obj)
{
throw new NotImplementedException();
}
public override RuntimeFieldHandle FieldHandle
{
get { throw new NotImplementedException(); }
}
public override Type FieldType { get { throw new NotImplementedException(); } }
public override Object GetValue(Object obj) { throw new InvalidOperationException(); }
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); }
public override FieldAttributes Attributes { get { return m_field.Attributes; } }
#endregion
}
}
| |
// String Processing (C) 2010 Robert MacGregor
//------------------------------------------------------------------------------
function strGetCRC(%text)
{
%fileObj = new fileObject(TextToHash);
%fileObj.openForWrite("crcTemp.txt");
%fileObj.writeLine(%text);
%fileObj.detach();
%result = getFileCRC("crcTemp.txt");
deleteFile("crcTemp.txt");
return %result;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function strReverse(%string)
{
%len = StrLen(%string);
%rstring = "";
for (%i = 0; %i < %len; %i++)
%rstring = getSubStr(%string,%i,1) @ %rstring;
return %rstring;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function subStrInsert(%string,%insert,%slot)
{
%seg = getSubStr(%string,0,%slot);
%seg = %seg @ %insert;
%string = %seg @ getSubStr(%string,%slot,strLen(%string));
return %string;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function subStrRemove(%string,%slot)//Minimum: 1
{
%half2 = getSubStr(%string,%slot,strLen(%string));
%half1 = getSubStr(%string,0,%slot-1);
return %half1 @ %half2;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function strMove(%string,%factor)
{
%len = GetWordCount(%string);
for (%i = 0; %i < %len; %i++)
{
%sub = getWord(%string,%i);
%move = subStrInsert(%move,%sub,%i);
}
return %move;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function subStrMove(%string, %factor)
{
%len = strLen(%string);
for (%i = 0; %i < %len; %i++)
{
%sub = getSubStr(%string, %i, 1);
%move = subStrInsert(%move, %sub, %factor);
}
return %move;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function subStrScramble(%string)
{
%len = strLen(%string);
for (%i = 0; %i < %len; %i++)
{
%sub = getSubStr(%string, %i, 1);
%scramble = subStrInsert(%scramble, %sub, getRandom(0,%len));
}
return %scramble;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function strSplit(%string)
{
%count = strLen(%string);
%div = %count / 2;
return getSubStr(%string, 0, %div) @ " | " @ getSubStr(%string,%div,%count);
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function stripSpaces(%string)
{
return strReplace(%string, " ", "");
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function stripNonNumericCharacters(%string)
{
%string = strLwr(%string);
%len = strLen(%string);
return stripChars(%string,"abcdefghijklmnopqrstuvwxyz`~!@#$%^&*()-_=+\|}]{[/?.>,<;:");
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function getSubStrOccurance(%string,%search)
{
%len = strLen(%string);
%srLen = strLen(%search);
%count = 0;
for (%i = 0; %i < %len; %i++)
{
%strSearch = strStr(%string,%search);
if (%strSearch != -1) //It exists somewhere in the string
{
%count++;
%string = getSubStr(%string,%strSearch+%srLen,%len);
}
else
return %count SPC %strSearch + %srLen;
}
return %count SPC %strSearch + %srLen;
}
function getSubStrPos(%string,%str,%num)
{
%len = strLen(%string);
%subC = 0;
for (%i = 0; %i < %len; %i++)
{
%sub = getSubStr(%string,%i,1);
if (%sub $= %str)
{
%subC++;
if (%subC == %num)
break;
}
}
return %i;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function getFileNameFromString(%string)
{
if (strStr(%string, "/") == -1)
return %string;
else
return getSubStr(%string,getSubStrPos(%string, "/", getSubStrOccurances(%string, "/")-1)+1,strLen(%string));
}
//------------------------------------------------------------------------------
function getFileExtensionFromString(%string)
{
%file = getFileNameFromString(%string);
%period = strStr(%file,".");
if (%period == -1)
return false;
else
return getSubStr(%file,strStr(%file,".")+1, strLen(%file));
}
//------------------------------------------------------------------------------
function strWhite(%string, %whiteList, %char)
{
%charLen = strLen(%char);
for (%i = 0; %i < strLen(%whiteList); %i++)
for (%h = 0; %h < %charLen; %h++)
{
%whiteSeg = getSubStr(%whiteList, %i, %charLen);
}
return false;
}
| |
/// Dedicated to the public domain by Christopher Diggins
/// http://creativecommons.org/licenses/publicdomain/
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Cat
{
/// <summary>
/// This class allwows us to convert Cat with named parameters,
/// to Cat without.
/// </summary>
public static class CatLambdaConverter
{
public static int gnId = 0;
public static void Convert(AstRoot p)
{
foreach (AstDef x in p.Defs)
Convert(x);
}
public static string GenerateUniqueName(string sArg)
{
return sArg + "$" + gnId++.ToString();
}
public static void RenameFirstInstance(string sOld, string sNew, List<CatAstNode> terms)
{
for (int i = 0; i < terms.Count; ++i)
{
if (TermContains(terms[i], sOld))
{
if (terms[i] is AstLambda)
{
AstLambda l = terms[i] as AstLambda;
RenameFirstInstance(sOld, sNew, l.mTerms);
return;
}
else if (terms[i] is AstQuote)
{
AstQuote q = terms[i] as AstQuote;
RenameFirstInstance(sOld, sNew, q.mTerms);
return;
}
else
{
// Should never happen.
throw new Exception("expected either a lamda node or quote node");
}
}
else if (TermEquals(terms[i], sOld))
{
terms[i] = new AstName(sNew);
return;
}
}
throw new Exception(sOld + " was not found in the list of terms");
}
public static bool TermEquals(CatAstNode term, string var)
{
return term.ToString().Equals(var);
}
public static bool TermContains(CatAstNode term, string var)
{
if (term is AstQuote)
{
AstQuote q = term as AstQuote;
foreach (CatAstNode child in q.mTerms)
{
if (TermContainsOrEquals(child, var))
return true;
}
return false;
}
else if (term is AstLambda)
{
AstLambda l = term as AstLambda;
foreach (CatAstNode child in l.mTerms)
{
if (TermContainsOrEquals(child, var))
return true;
}
return false;
}
else
{
return false;
}
}
public static int CountInstancesOf(string var, List<CatAstNode> terms)
{
int ret = 0;
foreach (CatAstNode term in terms)
{
if (term is AstQuote)
{
AstQuote q = term as AstQuote;
ret += CountInstancesOf(var, q.mTerms);
}
else if (term is AstLambda)
{
AstLambda l = term as AstLambda;
ret += CountInstancesOf(var, l.mTerms);
}
else
{
if (TermEquals(term, var))
ret += 1;
}
}
return ret;
}
public static bool TermContainsOrEquals(CatAstNode term, string var)
{
return TermEquals(term, var) || TermContains(term, var);
}
public static void RemoveTerm(string var, List<CatAstNode> terms)
{
// Find the first term that either contains, or is equal to the
// free variable
int i = 0;
while (i < terms.Count)
{
if (TermContainsOrEquals(terms[i], var))
break;
++i;
}
if (i == terms.Count)
throw new Exception("error in abstraction elimination algorithm");
if (i > 0)
{
AstQuote q = new AstQuote(terms.GetRange(0, i));
terms.RemoveRange(0, i);
terms.Insert(0, q);
terms.Insert(1, new AstName("dip"));
i = 2;
}
else
{
i = 0;
}
if (TermEquals(terms[i], var))
{
terms[i] = new AstName("id");
return;
}
else if (TermContains(terms[i], var))
{
if (terms[i] is AstQuote)
{
AstQuote subExpr = terms[i] as AstQuote;
RemoveTerm(var, subExpr.mTerms);
}
else if (TermContains(terms[i], var))
{
AstLambda subExpr = terms[i] as AstLambda;
RemoveTerm(var, subExpr.mTerms);
}
else
{
throw new Exception("internal error: expected either a quotation or lambda term");
}
terms.Insert(i + 1, new AstName("papply"));
return;
}
else
{
throw new Exception("error in abstraction elimination algorithm");
}
}
/* DEBUG:
private static string VarsToString(List<string> vars)
{
string ret = "";
foreach (string s in vars)
ret += s + " ";
return ret;
}
*/
/// <summary>
/// Converts a list of terms to point-free form.
/// </summary>
public static void ConvertTerms(List<string> vars, List<CatAstNode> terms)
{
for (int i = 0; i < terms.Count; ++i)
{
CatAstNode exp = terms[i];
if (exp is AstLambda)
Convert(exp as AstLambda);
}
if (vars.Count == 0)
return;
for (int i = 0; i < vars.Count; ++i)
{
string var = vars[i];
if (CountInstancesOf(var, terms) == 0)
{
// Remove unused arguments
terms.Insert(0, new AstName("pop"));
}
else
{
int nDupCount = 0;
while (CountInstancesOf(var, terms) > 1)
{
// Create a new name for the used argument
string sNewVar = GenerateUniqueName(var);
RenameFirstInstance(var, sNewVar, terms);
RemoveTerm(sNewVar, terms);
nDupCount++;
}
RemoveTerm(var, terms);
for (int j=0; j < nDupCount; ++j)
terms.Insert(0, new AstName("dup"));
}
}
}
public static void Convert(AstLambda l)
{
ConvertTerms(l.mIdentifiers, l.mTerms);
// We won't be needing the identifiers anymore and I don't want
// to have the conversion algorithm get run potentially multiple
// times on each lambda term.
l.mIdentifiers.Clear();
}
/// <summary>
/// This is known as an abstraction algorithm. It converts from
/// a form with named parameters to point-free form.
/// </summary>
/// <param name="sRightConsequent"></param>
public static void Convert(AstDef d)
{
if (IsPointFree(d))
return;
List<string> args = new List<string>();
foreach (AstParam p in d.mParams)
args.Add(p.ToString());
ConvertTerms(args, d.mTerms);
}
public static bool IsPointFree(AstRoot p)
{
foreach (AstDef d in p.Defs)
if (!IsPointFree(d))
return false;
return true;
}
public static bool IsPointFree(AstDef d)
{
return d.mParams.Count == 0;
}
}
}
| |
//
// 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 System.Xml;
using Hyak.Common;
using Microsoft.Azure.Insights;
using Microsoft.Azure.Insights.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Insights
{
/// <summary>
/// Operations for metric definitions.
/// </summary>
internal partial class MetricDefinitionOperations : IServiceOperations<InsightsClient>, IMetricDefinitionOperations
{
/// <summary>
/// Initializes a new instance of the MetricDefinitionOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal MetricDefinitionOperations(InsightsClient client)
{
this._client = client;
}
private InsightsClient _client;
/// <summary>
/// Gets a reference to the Microsoft.Azure.Insights.InsightsClient.
/// </summary>
public InsightsClient Client
{
get { return this._client; }
}
/// <summary>
/// The List Metric Definitions operation lists the metric definitions
/// for the resource.
/// </summary>
/// <param name='resourceUri'>
/// Required. The resource identifier of the target resource to get
/// metrics for.
/// </param>
/// <param name='filterString'>
/// Optional. An OData $filter expression that supports querying by the
/// name of the metric definition. For example, "name.value eq
/// 'Percentage CPU'". Name is optional, meaning the expression may be
/// "".
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The List Metric Definitions operation response.
/// </returns>
public async Task<MetricDefinitionListResponse> GetMetricDefinitionsAsync(string resourceUri, string filterString, CancellationToken cancellationToken)
{
// Validate
if (resourceUri == null)
{
throw new ArgumentNullException("resourceUri");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("filterString", filterString);
TracingAdapter.Enter(invocationId, this, "GetMetricDefinitionsAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/";
url = url + resourceUri;
url = url + "/metricDefinitions";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-07-01");
List<string> odataFilter = new List<string>();
if (filterString != null)
{
odataFilter.Add(Uri.EscapeDataString(filterString));
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-04-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
MetricDefinitionListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new MetricDefinitionListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
MetricDefinitionCollection metricDefinitionCollectionInstance = new MetricDefinitionCollection();
result.MetricDefinitionCollection = metricDefinitionCollectionInstance;
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
MetricDefinition metricDefinitionInstance = new MetricDefinition();
metricDefinitionCollectionInstance.Value.Add(metricDefinitionInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
LocalizableString nameInstance = new LocalizableString();
metricDefinitionInstance.Name = nameInstance;
JToken valueValue2 = nameValue["value"];
if (valueValue2 != null && valueValue2.Type != JTokenType.Null)
{
string valueInstance = ((string)valueValue2);
nameInstance.Value = valueInstance;
}
JToken localizedValueValue = nameValue["localizedValue"];
if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null)
{
string localizedValueInstance = ((string)localizedValueValue);
nameInstance.LocalizedValue = localizedValueInstance;
}
}
JToken unitValue = valueValue["unit"];
if (unitValue != null && unitValue.Type != JTokenType.Null)
{
Unit unitInstance = ((Unit)Enum.Parse(typeof(Unit), ((string)unitValue), true));
metricDefinitionInstance.Unit = unitInstance;
}
JToken primaryAggregationTypeValue = valueValue["primaryAggregationType"];
if (primaryAggregationTypeValue != null && primaryAggregationTypeValue.Type != JTokenType.Null)
{
AggregationType primaryAggregationTypeInstance = ((AggregationType)Enum.Parse(typeof(AggregationType), ((string)primaryAggregationTypeValue), true));
metricDefinitionInstance.PrimaryAggregationType = primaryAggregationTypeInstance;
}
JToken resourceIdValue = valueValue["resourceId"];
if (resourceIdValue != null && resourceIdValue.Type != JTokenType.Null)
{
string resourceIdInstance = ((string)resourceIdValue);
metricDefinitionInstance.ResourceId = resourceIdInstance;
}
JToken metricAvailabilitiesArray = valueValue["metricAvailabilities"];
if (metricAvailabilitiesArray != null && metricAvailabilitiesArray.Type != JTokenType.Null)
{
foreach (JToken metricAvailabilitiesValue in ((JArray)metricAvailabilitiesArray))
{
MetricAvailability metricAvailabilityInstance = new MetricAvailability();
metricDefinitionInstance.MetricAvailabilities.Add(metricAvailabilityInstance);
JToken timeGrainValue = metricAvailabilitiesValue["timeGrain"];
if (timeGrainValue != null && timeGrainValue.Type != JTokenType.Null)
{
TimeSpan timeGrainInstance = XmlConvert.ToTimeSpan(((string)timeGrainValue));
metricAvailabilityInstance.TimeGrain = timeGrainInstance;
}
JToken retentionValue = metricAvailabilitiesValue["retention"];
if (retentionValue != null && retentionValue.Type != JTokenType.Null)
{
TimeSpan retentionInstance = XmlConvert.ToTimeSpan(((string)retentionValue));
metricAvailabilityInstance.Retention = retentionInstance;
}
JToken locationValue = metricAvailabilitiesValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
MetricLocation locationInstance = new MetricLocation();
metricAvailabilityInstance.Location = locationInstance;
JToken tableEndpointValue = locationValue["tableEndpoint"];
if (tableEndpointValue != null && tableEndpointValue.Type != JTokenType.Null)
{
string tableEndpointInstance = ((string)tableEndpointValue);
locationInstance.TableEndpoint = tableEndpointInstance;
}
JToken tableInfoArray = locationValue["tableInfo"];
if (tableInfoArray != null && tableInfoArray.Type != JTokenType.Null)
{
foreach (JToken tableInfoValue in ((JArray)tableInfoArray))
{
MetricTableInfo metricTableInfoInstance = new MetricTableInfo();
locationInstance.TableInfo.Add(metricTableInfoInstance);
JToken tableNameValue = tableInfoValue["tableName"];
if (tableNameValue != null && tableNameValue.Type != JTokenType.Null)
{
string tableNameInstance = ((string)tableNameValue);
metricTableInfoInstance.TableName = tableNameInstance;
}
JToken startTimeValue = tableInfoValue["startTime"];
if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
{
DateTime startTimeInstance = ((DateTime)startTimeValue);
metricTableInfoInstance.StartTime = startTimeInstance;
}
JToken endTimeValue = tableInfoValue["endTime"];
if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
{
DateTime endTimeInstance = ((DateTime)endTimeValue);
metricTableInfoInstance.EndTime = endTimeInstance;
}
JToken sasTokenValue = tableInfoValue["sasToken"];
if (sasTokenValue != null && sasTokenValue.Type != JTokenType.Null)
{
string sasTokenInstance = ((string)sasTokenValue);
metricTableInfoInstance.SasToken = sasTokenInstance;
}
JToken sasTokenExpirationTimeValue = tableInfoValue["sasTokenExpirationTime"];
if (sasTokenExpirationTimeValue != null && sasTokenExpirationTimeValue.Type != JTokenType.Null)
{
DateTime sasTokenExpirationTimeInstance = ((DateTime)sasTokenExpirationTimeValue);
metricTableInfoInstance.SasTokenExpirationTime = sasTokenExpirationTimeInstance;
}
}
}
JToken partitionKeyValue = locationValue["partitionKey"];
if (partitionKeyValue != null && partitionKeyValue.Type != JTokenType.Null)
{
string partitionKeyInstance = ((string)partitionKeyValue);
locationInstance.PartitionKey = partitionKeyInstance;
}
}
JToken blobLocationValue = metricAvailabilitiesValue["blobLocation"];
if (blobLocationValue != null && blobLocationValue.Type != JTokenType.Null)
{
BlobLocation blobLocationInstance = new BlobLocation();
metricAvailabilityInstance.BlobLocation = blobLocationInstance;
JToken blobEndpointValue = blobLocationValue["blobEndpoint"];
if (blobEndpointValue != null && blobEndpointValue.Type != JTokenType.Null)
{
string blobEndpointInstance = ((string)blobEndpointValue);
blobLocationInstance.BlobEndpoint = blobEndpointInstance;
}
JToken blobInfoArray = blobLocationValue["blobInfo"];
if (blobInfoArray != null && blobInfoArray.Type != JTokenType.Null)
{
foreach (JToken blobInfoValue in ((JArray)blobInfoArray))
{
BlobInfo blobInfoInstance = new BlobInfo();
blobLocationInstance.BlobInfo.Add(blobInfoInstance);
JToken blobUriValue = blobInfoValue["blobUri"];
if (blobUriValue != null && blobUriValue.Type != JTokenType.Null)
{
string blobUriInstance = ((string)blobUriValue);
blobInfoInstance.BlobUri = blobUriInstance;
}
JToken startTimeValue2 = blobInfoValue["startTime"];
if (startTimeValue2 != null && startTimeValue2.Type != JTokenType.Null)
{
DateTime startTimeInstance2 = ((DateTime)startTimeValue2);
blobInfoInstance.StartTime = startTimeInstance2;
}
JToken endTimeValue2 = blobInfoValue["endTime"];
if (endTimeValue2 != null && endTimeValue2.Type != JTokenType.Null)
{
DateTime endTimeInstance2 = ((DateTime)endTimeValue2);
blobInfoInstance.EndTime = endTimeInstance2;
}
JToken sasTokenValue2 = blobInfoValue["sasToken"];
if (sasTokenValue2 != null && sasTokenValue2.Type != JTokenType.Null)
{
string sasTokenInstance2 = ((string)sasTokenValue2);
blobInfoInstance.SasToken = sasTokenInstance2;
}
}
}
}
}
}
JToken propertiesSequenceElement = ((JToken)valueValue["properties"]);
if (propertiesSequenceElement != null && propertiesSequenceElement.Type != JTokenType.Null)
{
foreach (JProperty property in propertiesSequenceElement)
{
string propertiesKey = ((string)property.Name);
string propertiesValue = ((string)property.Value);
metricDefinitionInstance.Properties.Add(propertiesKey, propertiesValue);
}
}
JToken dimensionsArray = valueValue["dimensions"];
if (dimensionsArray != null && dimensionsArray.Type != JTokenType.Null)
{
foreach (JToken dimensionsValue in ((JArray)dimensionsArray))
{
Dimension dimensionInstance = new Dimension();
metricDefinitionInstance.Dimensions.Add(dimensionInstance);
JToken nameValue2 = dimensionsValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
LocalizableString nameInstance2 = new LocalizableString();
dimensionInstance.Name = nameInstance2;
JToken valueValue3 = nameValue2["value"];
if (valueValue3 != null && valueValue3.Type != JTokenType.Null)
{
string valueInstance2 = ((string)valueValue3);
nameInstance2.Value = valueInstance2;
}
JToken localizedValueValue2 = nameValue2["localizedValue"];
if (localizedValueValue2 != null && localizedValueValue2.Type != JTokenType.Null)
{
string localizedValueInstance2 = ((string)localizedValueValue2);
nameInstance2.LocalizedValue = localizedValueInstance2;
}
}
JToken valuesArray = dimensionsValue["values"];
if (valuesArray != null && valuesArray.Type != JTokenType.Null)
{
foreach (JToken valuesValue in ((JArray)valuesArray))
{
LocalizableString localizableStringInstance = new LocalizableString();
dimensionInstance.Values.Add(localizableStringInstance);
JToken valueValue4 = valuesValue["value"];
if (valueValue4 != null && valueValue4.Type != JTokenType.Null)
{
string valueInstance3 = ((string)valueValue4);
localizableStringInstance.Value = valueInstance3;
}
JToken localizedValueValue3 = valuesValue["localizedValue"];
if (localizedValueValue3 != null && localizedValueValue3.Type != JTokenType.Null)
{
string localizedValueInstance3 = ((string)localizedValueValue3);
localizableStringInstance.LocalizedValue = localizedValueInstance3;
}
}
}
}
}
}
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using System;
using System.Windows;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Prism.Regions;
using Prism.Regions.Behaviors;
using Prism.Wpf.Tests.Mocks;
namespace Prism.Wpf.Tests.Regions.Behaviors
{
[TestClass]
public class RegionActiveAwareBehaviorFixture
{
[TestMethod]
public void SetsIsActivePropertyOnIActiveAwareObjects()
{
var region = new MockPresentationRegion();
region.RegionManager = new MockRegionManager();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var collection = region.MockActiveViews.Items;
ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement();
Assert.IsFalse(activeAwareObject.IsActive);
collection.Add(activeAwareObject);
Assert.IsTrue(activeAwareObject.IsActive);
collection.Remove(activeAwareObject);
Assert.IsFalse(activeAwareObject.IsActive);
}
[TestMethod]
public void SetsIsActivePropertyOnIActiveAwareDataContexts()
{
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var collection = region.MockActiveViews.Items;
ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement();
var frameworkElementMock = new Mock<FrameworkElement>();
var frameworkElement = frameworkElementMock.Object;
frameworkElement.DataContext = activeAwareObject;
Assert.IsFalse(activeAwareObject.IsActive);
collection.Add(frameworkElement);
Assert.IsTrue(activeAwareObject.IsActive);
collection.Remove(frameworkElement);
Assert.IsFalse(activeAwareObject.IsActive);
}
[TestMethod]
public void SetsIsActivePropertyOnBothIActiveAwareViewAndDataContext()
{
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var collection = region.MockActiveViews.Items;
var activeAwareMock = new Mock<IActiveAware>();
activeAwareMock.SetupProperty(o => o.IsActive);
var activeAwareObject = activeAwareMock.Object;
var frameworkElementMock = new Mock<FrameworkElement>();
frameworkElementMock.As<IActiveAware>().SetupProperty(o => o.IsActive);
var frameworkElement = frameworkElementMock.Object;
frameworkElement.DataContext = activeAwareObject;
Assert.IsFalse(((IActiveAware)frameworkElement).IsActive);
Assert.IsFalse(activeAwareObject.IsActive);
collection.Add(frameworkElement);
Assert.IsTrue(((IActiveAware)frameworkElement).IsActive);
Assert.IsTrue(activeAwareObject.IsActive);
collection.Remove(frameworkElement);
Assert.IsFalse(((IActiveAware)frameworkElement).IsActive);
Assert.IsFalse(activeAwareObject.IsActive);
}
[TestMethod]
public void DetachStopsListeningForChanges()
{
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
var collection = region.MockActiveViews.Items;
behavior.Attach();
behavior.Detach();
ActiveAwareFrameworkElement activeAwareObject = new ActiveAwareFrameworkElement();
collection.Add(activeAwareObject);
Assert.IsFalse(activeAwareObject.IsActive);
}
[TestMethod]
public void DoesNotThrowWhenAddingNonActiveAwareObjects()
{
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var collection = region.MockActiveViews.Items;
collection.Add(new object());
}
[TestMethod]
public void DoesNotThrowWhenAddingNonActiveAwareDataContexts()
{
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var collection = region.MockActiveViews.Items;
var frameworkElementMock = new Mock<FrameworkElement>();
var frameworkElement = frameworkElementMock.Object;
frameworkElement.DataContext = new object();
collection.Add(frameworkElement);
}
[TestMethod]
public void WhenParentViewGetsActivatedOrDeactivated_ThenChildViewIsNotUpdated()
{
var scopedRegionManager = new RegionManager();
var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager };
scopedRegionManager.Regions.Add(scopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new ActiveAwareFrameworkElement();
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, scopedRegionManager);
region.Activate(view);
scopedRegion.Add(childActiveAwareView);
scopedRegion.Activate(childActiveAwareView);
Assert.IsTrue(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsTrue(childActiveAwareView.IsActive);
}
[TestMethod]
public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewIsUpdated()
{
var scopedRegionManager = new RegionManager();
var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager };
scopedRegionManager.Regions.Add(scopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new SyncedActiveAwareObject();
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, scopedRegionManager);
region.Activate(view);
scopedRegion.Add(childActiveAwareView);
scopedRegion.Activate(childActiveAwareView);
Assert.IsTrue(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsFalse(childActiveAwareView.IsActive);
}
[TestMethod]
public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewWithAttributeInVMIsUpdated()
{
var scopedRegionManager = new RegionManager();
var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager };
scopedRegionManager.Regions.Add(scopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new ActiveAwareFrameworkElement();
childActiveAwareView.DataContext = new SyncedActiveAwareObjectViewModel();
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, scopedRegionManager);
region.Activate(view);
scopedRegion.Add(childActiveAwareView);
scopedRegion.Activate(childActiveAwareView);
Assert.IsTrue(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsFalse(childActiveAwareView.IsActive);
}
[TestMethod]
public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewModelThatIsNotAFrameworkElementIsNotUpdated()
{
var scopedRegionManager = new RegionManager();
var scopedRegion = new Region { Name = "MyScopedRegion", RegionManager = scopedRegionManager };
scopedRegionManager.Regions.Add(scopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new ActiveAwareObject();
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, scopedRegionManager);
region.Activate(view);
scopedRegion.Add(childActiveAwareView);
scopedRegion.Activate(childActiveAwareView);
Assert.IsTrue(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsTrue(childActiveAwareView.IsActive);
}
[TestMethod]
public void WhenParentViewGetsActivatedOrDeactivated_ThenSyncedChildViewNotInActiveViewsIsNotUpdated()
{
var scopedRegionManager = new RegionManager();
var scopedRegion = new Region { Name="MyScopedRegion", RegionManager = scopedRegionManager };
scopedRegionManager.Regions.Add(scopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = scopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new SyncedActiveAwareObject();
var region = new MockPresentationRegion();
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, scopedRegionManager);
region.Activate(view);
scopedRegion.Add(childActiveAwareView);
scopedRegion.Deactivate(childActiveAwareView);
Assert.IsFalse(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsFalse(childActiveAwareView.IsActive);
region.Activate(view);
Assert.IsFalse(childActiveAwareView.IsActive);
}
[TestMethod]
public void WhenParentViewWithoutScopedRegionGetsActivatedOrDeactivated_ThenSyncedChildViewIsNotUpdated()
{
var commonRegionManager = new RegionManager();
var nonScopedRegion = new Region { Name="MyRegion", RegionManager = commonRegionManager };
commonRegionManager.Regions.Add(nonScopedRegion);
var behaviorForScopedRegion = new RegionActiveAwareBehavior { Region = nonScopedRegion };
behaviorForScopedRegion.Attach();
var childActiveAwareView = new SyncedActiveAwareObject();
var region = new MockPresentationRegion { RegionManager = commonRegionManager };
var behavior = new RegionActiveAwareBehavior { Region = region };
behavior.Attach();
var view = new MockFrameworkElement();
region.Add(view);
RegionManager.SetRegionManager(view, commonRegionManager);
region.Activate(view);
nonScopedRegion.Add(childActiveAwareView);
nonScopedRegion.Activate(childActiveAwareView);
Assert.IsTrue(childActiveAwareView.IsActive);
region.Deactivate(view);
Assert.IsTrue(childActiveAwareView.IsActive);
}
class ActiveAwareObject : IActiveAware
{
public bool IsActive { get; set; }
public event EventHandler IsActiveChanged;
}
class ActiveAwareFrameworkElement : FrameworkElement, IActiveAware
{
public bool IsActive { get; set; }
public event EventHandler IsActiveChanged;
}
[SyncActiveState]
class SyncedActiveAwareObject : IActiveAware
{
public bool IsActive { get; set; }
public event EventHandler IsActiveChanged;
}
[SyncActiveState]
class SyncedActiveAwareObjectViewModel : IActiveAware
{
public bool IsActive { get; set; }
public event EventHandler IsActiveChanged;
}
}
}
| |
#define TRANSITION_ENABLED
//#define TRANSITION_POSTEFFECTS_ENABLED
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine.Extensions;
using UnityEngine.UI.Windows.Plugins.Flow;
using UnityEngine.UI.Windows.Animations;
using UnityEngine.UI.Extensions;
namespace UnityEngine.UI.Windows {
/// <summary>
/// Window or component object state.
/// </summary>
public enum WindowObjectState : byte {
NotInitialized = 0,
Initializing,
Initialized,
Showing,
Shown,
Hiding,
Hidden,
}
[ExecuteInEditMode()]
[RequireComponent(typeof(Camera))]
public class WindowBase : WindowObject, IWindowEventsAsync {
#if UNITY_EDITOR
[HideInInspector]
public bool editorInfoFold = false;
#endif
[HideInInspector]
public Camera workCamera;
[HideInInspector]
public bool initialized = false;
public Preferences preferences = new Preferences();
public Modules.Modules modules = new Modules.Modules();
public Events events = new Events();
#if !TRANSITION_ENABLED
[ReadOnly]
#endif
public Transition transition;
private int functionIterationIndex = 0;
[HideInInspector]
private bool setup = false;
[HideInInspector]
private bool passParams = false;
[HideInInspector]
private object[] parameters;
private WindowObjectState currentState = WindowObjectState.NotInitialized;
private WindowBase source;
public bool SourceEquals(WindowBase y) {
if (y == null) return false;
if (this.source == null) return y.source == this;
if (y.source == null) return y == this.source;
return this.source == y.source;
}
internal void Init(WindowBase source, float depth, float zDepth, int raycastPriority, int orderInLayer) {
this.source = source;
this.Init(depth, zDepth, raycastPriority, orderInLayer);
}
internal void Init(float depth, float zDepth, int raycastPriority, int orderInLayer) {
this.currentState = WindowObjectState.Initializing;
if (this.initialized == false) {
this.currentState = WindowObjectState.NotInitialized;
Debug.LogError("Can't initialize window instance because of some components was not installed properly.", this);
return;
}
var pos = this.transform.position;
pos.z = zDepth;
this.transform.position = pos;
this.workCamera.depth = depth;
if (this.preferences.IsDontDestroySceneChange() == true) {
GameObject.DontDestroyOnLoad(this.gameObject);
}
if (this.passParams == true) {
System.Reflection.MethodInfo methodInfo;
if (WindowSystem.InvokeMethodWithParameters(out methodInfo, this, "OnParametersPass", this.parameters) == true) {
// Success
methodInfo.Invoke(this, this.parameters);
} else {
// Method not found
Debug.LogWarning("Method `OnParametersPass` was not found with input parameters.", this);
}
} else {
this.OnEmptyPass();
}
if (this.setup == false) {
this.Setup(this);
this.OnTransitionInit();
this.OnLayoutInit(depth, raycastPriority, orderInLayer);
this.OnModulesInit();
this.OnInit();
this.setup = true;
}
this.currentState = WindowObjectState.Initialized;
}
public void SetFunctionIterationIndex(int iteration) {
this.functionIterationIndex = iteration;
}
public int GetFunctionIterationIndex() {
return this.functionIterationIndex;
}
internal void SetParameters(params object[] parameters) {
if (parameters != null && parameters.Length > 0) {
this.parameters = parameters;
this.passParams = true;
} else {
this.passParams = false;
}
}
/// <summary>
/// Gets the state.
/// </summary>
/// <returns>The state.</returns>
public WindowObjectState GetState() {
return this.currentState;
}
#if TRANSITION_POSTEFFECTS_ENABLED
private void OnRenderImage(RenderTexture source, RenderTexture destination) {
this.transition.OnRenderImage(source, destination);
}
private void OnPostRender() {
this.transition.OnPostRender();
}
private void OnPreRender() {
this.transition.OnPreRender();
}
#endif
private void OnTransitionInit() {
this.workCamera.clearFlags = CameraClearFlags.Depth;
this.transition.Setup(this);
this.transition.OnInit();
}
private void OnModulesInit() {
this.modules.Create(this, this.GetLayoutRoot());
this.modules.OnInit();
}
/// <summary>
/// Gets the name of the sorting layer.
/// </summary>
/// <returns>The sorting layer name.</returns>
public virtual string GetSortingLayerName() {
return string.Empty;
}
/// <summary>
/// Gets the sorting order.
/// </summary>
/// <returns>The sorting order.</returns>
public virtual int GetSortingOrder() {
return 0;
}
/// <summary>
/// Gets the duration of the animation.
/// </summary>
/// <returns>The animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public float GetAnimationDuration(bool forward) {
var layoutDuration = this.GetLayoutAnimationDuration(forward);
var moduleDuration = this.GetModuleAnimationDuration(forward);
var transitionDuration = this.GetTransitionAnimationDuration(forward);
return Mathf.Max(layoutDuration, Mathf.Max(moduleDuration, transitionDuration));
}
/// <summary>
/// Gets the duration of the transition animation.
/// </summary>
/// <returns>The transition animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetTransitionAnimationDuration(bool forward) {
return this.transition.GetAnimationDuration(forward);
}
/// <summary>
/// Gets the duration of the module animation.
/// </summary>
/// <returns>The module animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetModuleAnimationDuration(bool forward) {
return this.modules.GetAnimationDuration(forward);
}
/// <summary>
/// Gets the module.
/// </summary>
/// <returns>The module.</returns>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T GetModule<T>() where T : WindowModule {
return this.modules.Get<T>();
}
/// <summary>
/// Show this instance.
/// </summary>
public void Show() {
this.Show(null);
}
/// <summary>
/// Show the specified onShowEnd.
/// </summary>
/// <param name="onShowEnd">On show end.</param>
public void Show(System.Action onShowEnd) {
this.Show(onShowEnd, null, null);
}
/// <summary>
/// Show window with specific transition.
/// </summary>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public void Show(TransitionBase transition, TransitionInputParameters transitionParameters) {
this.Show(null, transition, transitionParameters);
}
/// <summary>
/// Show the specified onShowEnd.
/// </summary>
/// <param name="onShowEnd">On show end.</param>
public void Show(System.Action onShowEnd, TransitionBase transition, TransitionInputParameters transitionParameters) {
if (this.currentState == WindowObjectState.Showing || this.currentState == WindowObjectState.Shown) return;
this.currentState = WindowObjectState.Showing;
WindowSystem.AddToHistory(this);
var counter = 0;
System.Action callback = () => {
if (this.currentState != WindowObjectState.Showing) return;
++counter;
if (counter < 5) return;
this.OnShowEnd();
this.OnLayoutShowEnd();
this.modules.OnShowEnd();
this.events.OnShowEnd();
this.transition.OnShowEnd();
if (onShowEnd != null) onShowEnd();
CanvasUpdater.ForceUpdate();
this.currentState = WindowObjectState.Shown;
};
this.OnLayoutShowBegin(callback);
this.modules.OnShowBegin(callback);
if (transition != null) {
this.transition.OnShowBegin(transition, transitionParameters, callback);
} else {
this.transition.OnShowBegin(callback);
}
this.events.OnShowBegin(callback);
this.OnShowBegin(callback);
this.gameObject.SetActive(true);
}
/// <summary>
/// Hide this instance.
/// </summary>
public bool Hide() {
return this.Hide(null);
}
/// <summary>
/// Hide window with specific transition.
/// </summary>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public bool Hide(TransitionBase transition, TransitionInputParameters transitionParameters) {
return this.Hide(null, transition, transitionParameters);
}
/// <summary>
/// Hide the specified onHideEnd.
/// Wait while all components, animations, events and modules return the callback.
/// </summary>
/// <param name="onHideEnd">On hide end.</param>
public bool Hide(System.Action onHideEnd) {
return this.Hide(onHideEnd, null, null);
}
/// <summary>
/// Hide the specified onHideEnd with specific transition.
/// Wait while all components, animations, events and modules return the callback.
/// </summary>
/// <param name="onHideEnd">On hide end.</param>
/// <param name="transition">Transition.</param>
/// <param name="transitionParameters">Transition parameters.</param>
public bool Hide(System.Action onHideEnd, TransitionBase transition, TransitionInputParameters transitionParameters) {
if (this.currentState == WindowObjectState.Hidden || this.currentState == WindowObjectState.Hiding) return false;
this.currentState = WindowObjectState.Hiding;
var counter = 0;
System.Action callback = () => {
if (this.currentState != WindowObjectState.Hiding) return;
++counter;
if (counter < 5) return;
WindowSystem.AddToHistory(this);
this.Recycle();
this.OnHideEnd();
this.OnLayoutHideEnd();
this.modules.OnHideEnd();
this.events.OnHideEnd();
this.transition.OnHideEnd();
if (onHideEnd != null) onHideEnd();
this.currentState = WindowObjectState.Hidden;
};
this.OnLayoutHideBegin(callback);
this.modules.OnHideBegin(callback);
if (transition != null) {
this.transition.OnHideBegin(transition, transitionParameters, callback);
} else {
this.transition.OnHideBegin(callback);
}
this.events.OnHideBegin(callback);
this.OnHideBegin(callback, immediately: false);
return true;
}
private void OnDestroy() {
if (Application.isPlaying == false) return;
this.OnLayoutDeinit();
this.events.OnDeinit();
this.modules.OnDeinit();
this.transition.OnDeinit();
this.events.OnDeinit();
this.OnDeinit();
}
protected virtual Transform GetLayoutRoot() { return null; }
/// <summary>
/// Gets the duration of the layout animation.
/// </summary>
/// <returns>The layout animation duration.</returns>
/// <param name="forward">If set to <c>true</c> forward.</param>
public virtual float GetLayoutAnimationDuration(bool forward) {
return 0f;
}
/// <summary>
/// Raises the layout init event.
/// </summary>
/// <param name="depth">Depth.</param>
/// <param name="raycastPriority">Raycast priority.</param>
/// <param name="orderInLayer">Order in layer.</param>
protected virtual void OnLayoutInit(float depth, int raycastPriority, int orderInLayer) {}
/// <summary>
/// Raises the layout deinit event.
/// </summary>
protected virtual void OnLayoutDeinit() {}
/// <summary>
/// Raises the layout show begin event.
/// </summary>
/// <param name="callback">Callback.</param>
protected virtual void OnLayoutShowBegin(System.Action callback) { if (callback != null) callback(); }
/// <summary>
/// Raises the layout show end event.
/// </summary>
protected virtual void OnLayoutShowEnd() {}
/// <summary>
/// Raises the layout hide begin event.
/// </summary>
/// <param name="callback">Callback.</param>
protected virtual void OnLayoutHideBegin(System.Action callback) { if (callback != null) callback(); }
/// <summary>
/// Raises the layout hide end event.
/// </summary>
protected virtual void OnLayoutHideEnd() {}
/// <summary>
/// Raises the parameters pass event.
/// Don't override this method - use your own.
/// Window will use reflection to determine your method.
/// Example: OnParametersPass(T1 param1, T2 param2, etc.)
/// You can use any types in any order and call window with them.
/// </summary>
public virtual void OnParametersPass() {}
/// <summary>
/// Raises the empty pass event.
/// </summary>
public virtual void OnEmptyPass() {}
/// <summary>
/// Raises the init event.
/// </summary>
public virtual void OnInit() {}
/// <summary>
/// Raises the deinit event.
/// </summary>
public virtual void OnDeinit() {}
/// <summary>
/// Raises the show begin event.
/// </summary>
/// <param name="callback">Callback.</param>
public virtual void OnShowBegin(System.Action callback, bool resetAnimation = true) { if (callback != null) callback(); }
/// <summary>
/// Raises the show end event.
/// </summary>
public virtual void OnShowEnd() {}
/// <summary>
/// Raises the hide begin event.
/// </summary>
/// <param name="callback">Callback.</param>
public virtual void OnHideBegin(System.Action callback, bool immediately = false) { if (callback != null) callback(); }
/// <summary>
/// Raises the hide end event.
/// </summary>
public virtual void OnHideEnd() {}
#if UNITY_EDITOR
/// <summary>
/// Raises the validate event. Editor only.
/// </summary>
public virtual void OnValidate() {
this.preferences.OnValidate();
this.SetupCamera();
}
private void SetupCamera() {
this.workCamera = this.GetComponent<Camera>();
if (this.workCamera == null) {
this.workCamera = this.gameObject.AddComponent<Camera>();
}
if (this.workCamera != null) {
// Camera
WindowSystem.ApplyToSettings(this.workCamera);
if ((this.workCamera.cullingMask & (1 << this.gameObject.layer)) == 0) {
this.workCamera.cullingMask = 0x0;
this.workCamera.cullingMask |= 1 << this.gameObject.layer;
}
this.workCamera.backgroundColor = new Color(0f, 0f, 0f, 0f);
}
this.initialized = (this.workCamera != null);
}
#endif
}
}
| |
using System.Linq;
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine.Experimental.VFX;
using UnityEditor.Experimental.VFX;
using System;
namespace UnityEditor.VFX.UI
{
abstract class VFXUIController<T> : Controller<VFXUI> where T : VFXUI.UIInfo
{
protected int m_Index;
protected VFXUI m_UI;
public void Remove()
{
m_Index = -1;
}
abstract protected T[] infos {get; }
protected VFXViewController m_ViewController;
public int index
{
get { return m_Index; }
set { m_Index = value; }
}
void OnModelChanged()
{
ModelChanged(m_UI);
}
protected override void ModelChanged(UnityEngine.Object obj)
{
if (m_Index == -1) return;
NotifyChange(AnyThing);
}
public override void OnDisable()
{
m_ViewController.UnRegisterNotification(m_UI, OnModelChanged);
base.OnDisable();
}
public VFXUIController(VFXViewController viewController, VFXUI ui, int index) : base(ui)
{
m_UI = ui;
viewController.RegisterNotification(m_UI, OnModelChanged);
m_Index = index;
m_ViewController = viewController;
}
protected void ValidateRect(ref Rect r)
{
if (float.IsInfinity(r.x) || float.IsNaN(r.x))
{
r.x = 0;
}
if (float.IsInfinity(r.y) || float.IsNaN(r.y))
{
r.y = 0;
}
if (float.IsInfinity(r.width) || float.IsNaN(r.width))
{
r.width = 100;
}
if (float.IsInfinity(r.height) || float.IsNaN(r.height))
{
r.height = 100;
}
r.x = Mathf.Round(r.x);
r.y = Mathf.Round(r.y);
r.width = Mathf.Round(r.width);
r.height = Mathf.Round(r.height);
}
public Rect position
{
get
{
if (m_Index < 0)
{
return Rect.zero;
}
Rect result = infos[m_Index].position;
ValidateRect(ref result);
return result;
}
set
{
if (m_Index < 0) return;
ValidateRect(ref value);
infos[m_Index].position = value;
Modified();
}
}
public string title
{
get
{
if (m_Index < 0)
{
return "";
}
return infos[m_Index].title;
}
set
{
if (title != value && m_Index >= 0)
{
infos[m_Index].title = value;
Modified();
}
}
}
protected void Modified()
{
m_UI.Modified();
m_ViewController.IncremenentGraphUndoRedoState(null, VFXModel.InvalidationCause.kUIChanged);
}
public override void ApplyChanges()
{
if (m_Index == -1) return;
ModelChanged(model);
}
}
class VFXGroupNodeController : VFXUIController<VFXUI.GroupInfo>
{
public VFXGroupNodeController(VFXViewController viewController, VFXUI ui, int index) : base(viewController, ui, index)
{
}
public IEnumerable<Controller> nodes
{
get
{
if (m_Index == -1) return Enumerable.Empty<Controller>();
if (m_UI.groupInfos[m_Index].contents != null)
return m_UI.groupInfos[m_Index].contents.Where(t => t.isStickyNote || t.model != null).Select(t => t.isStickyNote ? (Controller)m_ViewController.GetStickyNoteController(t.id) : (Controller)m_ViewController.GetRootNodeController(t.model, t.id)).Where(t => t != null);
return Enumerable.Empty<Controller>();
}
}
override protected VFXUI.GroupInfo[] infos {get {return m_UI.groupInfos; }}
void AddNodeID(VFXNodeID nodeID)
{
if (m_Index < 0)
return;
if (m_UI.groupInfos[m_Index].contents != null)
m_UI.groupInfos[m_Index].contents = m_UI.groupInfos[m_Index].contents.Concat(Enumerable.Repeat(nodeID, 1)).Distinct().ToArray();
else
m_UI.groupInfos[m_Index].contents = new VFXNodeID[] { nodeID };
}
public void AddNodes(IEnumerable<VFXNodeController> controllers)
{
if (m_Index < 0)
return;
foreach (var controller in controllers)
{
AddNodeID(new VFXNodeID(controller.model, controller.id));
}
Modified();
}
public void AddNode(VFXNodeController controller)
{
if (m_Index < 0)
return;
AddNodeID(new VFXNodeID(controller.model, controller.id));
Modified();
}
public void AddStickyNotes(IEnumerable<VFXStickyNoteController> notes)
{
if (m_Index < 0)
return;
foreach (var note in notes)
{
AddNodeID(new VFXNodeID(note.index));
}
Modified();
}
public void AddStickyNote(VFXStickyNoteController note)
{
if (m_Index < 0)
return;
AddNodeID(new VFXNodeID(note.index));
Modified();
}
public void RemoveNodes(IEnumerable<VFXNodeController> nodeControllers)
{
if (m_Index < 0)
return;
if (m_UI.groupInfos[m_Index].contents == null)
return;
bool oneFound = false;
foreach (var nodeController in nodeControllers)
{
int id = nodeController.id;
var model = nodeController.model;
if (!m_UI.groupInfos[m_Index].contents.Any(t => t.model == model && t.id == id))
continue;
m_UI.groupInfos[m_Index].contents = m_UI.groupInfos[m_Index].contents.Where(t => t.model != model || t.id != id).ToArray();
oneFound = true;
}
if(oneFound)
Modified();
}
public void RemoveNode(VFXNodeController nodeController)
{
if (m_Index < 0)
return;
if (m_UI.groupInfos[m_Index].contents == null)
return;
int id = nodeController.id;
var model = nodeController.model;
if (!m_UI.groupInfos[m_Index].contents.Any(t => t.model == model && t.id == id))
return;
m_UI.groupInfos[m_Index].contents = m_UI.groupInfos[m_Index].contents.Where(t => t.model != model || t.id != id).ToArray();
Modified();
}
public void RemoveStickyNotes(IEnumerable<VFXStickyNoteController> stickyNodeControllers)
{
if (m_Index < 0)
return;
if (m_UI.groupInfos[m_Index].contents == null)
return;
foreach (var stickyNoteController in stickyNodeControllers)
{
if (!m_UI.groupInfos[m_Index].contents.Any(t => t.isStickyNote && t.id == stickyNoteController.index))
return;
m_UI.groupInfos[m_Index].contents = m_UI.groupInfos[m_Index].contents.Where(t => !t.isStickyNote || t.id != stickyNoteController.index).ToArray();
}
Modified();
}
public bool ContainsNode(VFXNodeController controller)
{
if (m_Index == -1) return false;
if (m_UI.groupInfos[m_Index].contents != null)
{
return m_UI.groupInfos[m_Index].contents.Contains(new VFXNodeID(controller.model, controller.id));
}
return false;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 3/8/2008 4:44:51 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using DotSpatial.Data;
using DotSpatial.Projections;
using DotSpatial.Serialization;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
[ToolboxItem(false)]
public class Layer : RenderableLegendItem, ILayer
{
#region Events
/// <summary>
/// Occurs if this layer was selected
/// </summary>
public event EventHandler<LayerSelectedEventArgs> LayerSelected;
/// <summary>
/// Occurs if the maps should zoom to this layer.
/// </summary>
public event EventHandler<EnvelopeArgs> ZoomToLayer;
/// <summary>
/// Occurs before the properties are actually shown, also allowing the event to be handled.
/// </summary>
public event HandledEventHandler ShowProperties;
/// <summary>
/// Occurs when all aspects of the layer finish loading.
/// </summary>
public event EventHandler FinishedLoading;
/// <summary>
/// Occurs after the selection is changed
/// </summary>
public event EventHandler SelectionChanged;
/// <summary>
/// Occurs when layer disposed.
/// </summary>
public event EventHandler Disposed;
#endregion Events
#region Private Variables
private IDataSet _dataSet;
private int _disposeLockCount;
private Extent _invalidatedRegion; // When a region is invalidated instead of the whole layer.
private bool _isDisposed;
private IProgressHandler _progressHandler;
private ProgressMeter _progressMeter;
private ProjectionInfo _projection;
private string _projectionString;
private IPropertyDialogProvider _propertyDialogProvider;
private bool _selectionEnabled;
#endregion Private Variables
#region Constructors
/// <summary>
/// Creates a new Layer, but this should be done from the derived classes
/// </summary>
protected Layer()
{
// InitializeComponent();
Configure();
}
/// <summary>
/// Creates a new Layer, but this should be done from the derived classes
/// </summary>
/// <param name="container">The container this layer should be a member of</param>
protected Layer(ICollection<ILayer> container)
{
if (container != null) container.Add(this);
Configure();
}
/// <summary>
/// Creates a new layer with only a progress handler
/// </summary>
/// <param name="progressHandler"></param>
protected Layer(IProgressHandler progressHandler)
{
_progressHandler = progressHandler;
Configure();
}
/// <summary>
/// Creates a new Layer, but this should be done from the derived classes
/// </summary>
/// <param name="container">The container this layer should be a member of</param>
/// <param name="progressHandler">A progress handler for handling progress messages</param>
protected Layer(ICollection<ILayer> container, IProgressHandler progressHandler)
{
_progressHandler = progressHandler;
if (container != null) container.Add(this);
Configure();
}
private void Configure()
{
_selectionEnabled = true;
base.ContextMenuItems = new List<SymbologyMenuItem>
{
new SymbologyMenuItem(SymbologyMessageStrings.RemoveLayer, SymbologyImages.mnuLayerClear,
RemoveLayerClick),
new SymbologyMenuItem(SymbologyMessageStrings.ZoomToLayer, SymbologyImages.ZoomInMap,
ZoomToLayerClick),
new SymbologyMenuItem(SymbologyMessageStrings.SetDynamicVisibilityScale, SymbologyImages.ZoomScale,
SetDynamicVisibility)
};
SymbologyMenuItem mnuData = new SymbologyMenuItem(SymbologyMessageStrings.Data);
mnuData.MenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.ExportData, SymbologyImages.save, ExportDataClick));
base.ContextMenuItems.Add(mnuData);
base.ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.Properties, SymbologyImages.color_scheme, ShowPropertiesClick));
base.LegendSymbolMode = SymbolMode.Checkbox;
LegendType = LegendType.Layer;
base.IsExpanded = true;
}
private void PropertyDialogProviderChangesApplied(object sender, ChangedObjectEventArgs e)
{
CopyProperties(e.Item as ILegendItem);
}
#endregion Constructors
#region Methods
/// <summary>
/// Given a geographic extent, this tests the "IsVisible", "UseDynamicVisibility",
/// "DynamicVisibilityMode" and "DynamicVisibilityWidth"
/// In order to determine if this layer is visible for the specified scale.
/// </summary>
/// <param name="geographicExtent">The geographic extent, where the width will be tested.</param>
/// <returns>Boolean, true if this layer should be visible for this extent.</returns>
public bool VisibleAtExtent(Extent geographicExtent)
{
if (!IsVisible) return false;
if (UseDynamicVisibility)
{
if (DynamicVisibilityMode == DynamicVisibilityMode.ZoomedIn)
{
if (geographicExtent.Width > DynamicVisibilityWidth)
{
return false; // skip the geoLayer if we are zoomed out too far.
}
}
else
{
if (geographicExtent.Width < DynamicVisibilityWidth)
{
return false; // skip the geoLayer if we are zoomed in too far.
}
}
}
return true;
}
/// <summary>
/// Tests the specified legend item. If the item is another layer or a group or a map-frame, then this
/// will return false. Furthermore, if the parent of the item is not also this object, then it will
/// also return false. The idea is that layers can have sub-nodes move around, but not transport from
/// place to place.
/// </summary>
/// <param name="item">the legend item to test</param>
/// <returns>Boolean that if true means that it is ok to insert the specified item into this layer.</returns>
public override bool CanReceiveItem(ILegendItem item)
{
if (item.GetParentItem() != this) return false;
var lyr = item as ILayer;
if (lyr != null) return false;
return true;
}
/// <summary>
/// Queries this layer and the entire parental tree up to the map frame to determine if
/// this layer is within the selected layers.
/// </summary>
public bool IsWithinLegendSelection()
{
if (IsSelected) return true;
ILayer lyr = GetParentItem() as ILayer;
while (lyr != null)
{
if (lyr.IsSelected) return true;
lyr = lyr.GetParentItem() as ILayer;
}
return false;
}
/// <summary>
/// Notifies the layer that the next time an area that intersects with this region
/// is specified, it must first re-draw content to the image buffer.
/// </summary>
/// <param name="region">The envelope where content has become invalidated.</param>
public virtual void Invalidate(Extent region)
{
if (_invalidatedRegion != null)
{
// This is set to null when we do the redrawing, so we would rather expand
// the redraw region than forget to update a modified area.
_invalidatedRegion.ExpandToInclude(region);
}
else
{
_invalidatedRegion = region;
}
}
/// <summary>
/// Notifies parent layer that this item is invalid and should be redrawn.
/// </summary>
public override void Invalidate()
{
OnItemChanged(this);
}
private void SetDynamicVisibility(object sender, EventArgs e)
{
var la = LayerActions;
if (la != null)
{
la.DynamicVisibility(this, MapFrame);
}
}
#endregion Methods
#region Properties
/// <summary>
/// Gets or sets custom actions for Layer
/// </summary>
[Browsable(false)]
public ILayerActions LayerActions { get; set; }
/// <summary>
/// Gets or sets the internal data set. This can be null, as in the cases of groups or map-frames.
/// Copying a layer should not create a duplicate of the dataset, but rather it should point to the
/// original dataset. The ShallowCopy attribute is used so even though the DataSet itself may be cloneable,
/// cloning a layer will treat the dataset like a shallow copy.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[ShallowCopy]
public IDataSet DataSet
{
get { return _dataSet; }
set
{
if (_dataSet == value) return;
if (_dataSet != null)
{
_dataSet.UnlockDispose();
if (!_dataSet.IsDisposeLocked)
{
_dataSet.Dispose();
}
}
_dataSet = value;
if (_dataSet != null)
{
_dataSet.LockDispose();
}
}
}
/// <summary>
/// Dynamic visibility represents layers that only appear when you zoom in close enough.
/// This value represents the geographic width where that happens.
/// </summary>
[Serialize("DynamicVisibilityWidth"), Category("Behavior"), Description("Dynamic visibility represents layers that only appear when the zoom scale is closer (or further) from a set scale. This value represents the geographic width where the change takes place.")]
public double DynamicVisibilityWidth { get; set; }
/// <summary>
/// This controls whether the layer is visible when zoomed in closer than the dynamic
/// visibility width or only when further away from the dynamic visibility width
/// </summary>
[Serialize("DynamicVisibilityMode"), Category("Behavior"), Description("This controls whether the layer is visible when zoomed in closer than the dynamic visiblity width or only when further away from the dynamic visibility width")]
public DynamicVisibilityMode DynamicVisibilityMode { get; set; }
/// <summary>
/// Gets the currently invalidated region.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Extent InvalidRegion
{
get { return _invalidatedRegion; }
protected set { _invalidatedRegion = value; }
}
/// <summary>
/// Gets the map frame of the parent LayerCollection.
/// </summary>
[Browsable(false), ShallowCopy]
public virtual IFrame MapFrame { get; set; }
/// <summary>
/// Gets or sets the ProgressHandler for this layer. Setting this overrides the default
/// behavior which is to use the
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IProgressHandler ProgressHandler
{
get
{
if (_progressHandler != null) return _progressHandler;
return DataManager.DefaultDataManager.ProgressHandler;
}
set
{
_progressHandler = value;
if (_progressMeter == null) _progressMeter = new ProgressMeter(_progressHandler);
_progressMeter.ProgressHandler = value;
}
}
/// <summary>
/// Gets or sets a boolean indicating whether to allow the dynamic visibility
/// envelope to control visibility.
/// </summary>
[Serialize("UseDynamicVisibility"), Category("Behavior"), Description("Gets or sets a boolean indicating whether to allow the dynamic visibility envelope to control visibility.")]
public bool UseDynamicVisibility { get; set; }
/// <inheritdoc />
[Category("Behavior"), Description("Gets or sets a boolean indicating whether this layer is selected in the legend.")]
public override bool IsSelected
{
get
{
return base.IsSelected;
}
set
{
if (base.IsSelected != value)
{
base.IsSelected = value;
OnLayerSelected(this, value);
}
}
}
/// <inheritdoc />
[Serialize("IsVisible")]
[Category("Behavior"), Description("Gets or sets a boolean indicating whether this layer is visible in the map.")]
public override bool IsVisible
{
get
{
return base.IsVisible;
}
set
{
base.IsVisible = value;
}
}
#endregion Properties
#region Protected Methods
/// <summary>
/// Fires the zoom to layer event.
/// </summary>
protected virtual void OnZoomToLayer()
{
var h = ZoomToLayer;
if (h != null && !Extent.IsEmpty()) // changed by jany_ (2015-07-17) zooming to an empty layer makes no sense
{
h(this, new EnvelopeArgs(Extent.ToEnvelope()));
}
}
/// <summary>
/// Fires the zoom to layer event, but specifies the extent.
/// </summary>
/// <param name="env">Envelope env</param>
protected virtual void OnZoomToLayer(Envelope env)
{
var h = ZoomToLayer;
if (h != null)
{
h(this, new EnvelopeArgs(env));
}
}
#endregion Protected Methods
#region EventHandlers
private void ExportDataClick(object sender, EventArgs e)
{
OnExportData();
}
private void ShowPropertiesClick(object sender, EventArgs e)
{
// Allow subclasses to prevent this class from showing the default dialog
HandledEventArgs result = new HandledEventArgs(false);
OnShowProperties(result);
if (result.Handled) return;
if (_propertyDialogProvider == null) return;
var editCopy = CloneableEM.Copy(this);
CopyProperties(editCopy); // for some reason we are getting blank layers during edits, this tries to fix that
_propertyDialogProvider.ShowDialog(editCopy);
editCopy.Dispose();
LayerManager.DefaultLayerManager.ActiveProjectLayers = new List<ILayer>();
}
#endregion EventHandlers
#region Protected Methods
/// <summary>
/// Layers launch a "Property Grid" by default. However, this can be overridden with a different UIEditor by this
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual IPropertyDialogProvider PropertyDialogProvider
{
get
{
return _propertyDialogProvider;
}
protected set
{
if (_propertyDialogProvider != null)
{
_propertyDialogProvider.ChangesApplied -= PropertyDialogProviderChangesApplied;
}
_propertyDialogProvider = value;
if (_propertyDialogProvider != null)
{
base.ContextMenuItems.Add(new SymbologyMenuItem(SymbologyMessageStrings.Layer_Properties, ShowPropertiesClick));
_propertyDialogProvider.ChangesApplied += PropertyDialogProviderChangesApplied;
}
}
}
/// <summary>
/// Occurs before showing the properties dialog. If the handled member
/// was set to true, then this class will not show the event args.
/// </summary>
/// <param name="e"></param>
protected virtual void OnShowProperties(HandledEventArgs e)
{
var h = ShowProperties;
if (h != null) h(this, e);
}
/// <summary>
/// This should be overridden to copy the symbolizer properties from editCopy
/// </summary>
/// <param name="editCopy">The version that went into the property dialog</param>
protected override void OnCopyProperties(object editCopy)
{
ILayer layer = editCopy as ILayer;
if (layer != null)
{
SuspendChangeEvent();
base.OnCopyProperties(editCopy);
ResumeChangeEvent();
}
}
/// <summary>
/// Zooms to the specific layer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ZoomToLayerClick(object sender, EventArgs e)
{
OnZoomToLayer();
}
/// <summary>
/// Removes this layer from its parent list
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void RemoveLayerClick(object sender, EventArgs e)
{
OnRemoveItem();
}
/// <summary>
/// Fires the LayerSelected event
/// </summary>
protected virtual void OnLayerSelected(ILayer sender, bool selected)
{
var h = LayerSelected;
if (h != null) h(this, new LayerSelectedEventArgs(sender, selected));
}
/// <summary>
/// Fires the OnFinishedLoading event.
/// </summary>
protected void OnFinishedLoading()
{
var h = FinishedLoading;
if (h != null) h(this, EventArgs.Empty);
}
/// <summary>
/// Occurs when instructions are being sent for this layer to export data.
/// </summary>
protected virtual void OnExportData()
{
}
/// <summary>
/// special treatment for event handlers during a copy event
/// </summary>
/// <param name="copy"></param>
protected override void OnCopy(Descriptor copy)
{
// Remove event handlers from the copy. (They will be set again when adding to a new map.)
Layer copyLayer = copy as Layer;
if (copyLayer == null) return;
if (copyLayer.LayerSelected != null)
{
foreach (var handler in copyLayer.LayerSelected.GetInvocationList())
{
copyLayer.LayerSelected -= (EventHandler<LayerSelectedEventArgs>)handler;
}
}
if (copyLayer.ZoomToLayer != null)
{
foreach (var handler in copyLayer.ZoomToLayer.GetInvocationList())
{
copyLayer.ZoomToLayer -= (EventHandler<EnvelopeArgs>)handler;
}
}
if (copyLayer.ShowProperties != null)
{
foreach (var handler in copyLayer.ShowProperties.GetInvocationList())
{
copyLayer.ShowProperties -= (HandledEventHandler)handler;
}
}
if (copyLayer.FinishedLoading != null)
{
foreach (var handler in copyLayer.FinishedLoading.GetInvocationList())
{
copyLayer.FinishedLoading -= (EventHandler)handler;
}
}
if (copyLayer.SelectionChanged != null)
{
foreach (var handler in copyLayer.SelectionChanged.GetInvocationList())
{
copyLayer.SelectionChanged -= (EventHandler)handler;
}
}
base.OnCopy(copy);
}
#endregion Protected Methods
#region Protected Properties
/// <summary>
/// Gets or sets the progress meter being used internally by layer classes.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
protected ProgressMeter ProgressMeter
{
get { return _progressMeter ?? (_progressMeter = new ProgressMeter(ProgressHandler)); }
set { _progressMeter = value; }
}
#endregion Protected Properties
#region Static Methods
/// <summary>
/// Opens a fileName using the default layer provider and returns a new layer. The layer will not automatically have a container or be added to a map.
/// </summary>
/// <param name="fileName">The string fileName of the layer to open</param>
/// <returns>An ILayer interface</returns>
public static ILayer OpenFile(string fileName)
{
if (File.Exists(fileName) == false) return null;
return LayerManager.DefaultLayerManager.OpenLayer(fileName);
}
/// <summary>
/// Opens a fileName using the default layer provider and returns a new layer. The layer will not automatically have a container or be added to a map.
/// </summary>
/// <param name="fileName">The string fileName of the layer to open</param>
/// <param name="progressHandler">An IProgresshandler that overrides the Default Layer Manager's progress handler</param>
/// <returns>An ILayer interface with the new layer.</returns>
public static ILayer OpenFile(string fileName, IProgressHandler progressHandler)
{
return File.Exists(fileName) == false ? null : LayerManager.DefaultLayerManager.OpenLayer(fileName, progressHandler);
}
/// <summary>
/// Opens a new layer and automatically adds it to the specified container.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="container">The container (usually a LayerCollection) to add to</param>
/// <returns>The layer after it has been created and added to the container</returns>
public static ILayer OpenFile(string fileName, ICollection<ILayer> container)
{
if (File.Exists(fileName) == false) return null;
ILayerManager dm = LayerManager.DefaultLayerManager;
return dm.OpenLayer(fileName, container);
}
/// <summary>
/// Attempts to call the open fileName method for any ILayerProvider plugin
/// that matches the extension on the string.
/// </summary>
/// <param name="fileName">A String fileName to attempt to open.</param>
/// <param name="inRam">A boolean value that if true will attempt to force a load of the data into memory. This value overrides the property on this LayerManager.</param>
/// <param name="container">A container to open this layer in</param>
/// <param name="progressHandler">Specifies the progressHandler to receive progress messages. This value overrides the property on this LayerManager.</param>
/// <returns>An ILayer</returns>
public virtual ILayer OpenLayer(string fileName, bool inRam, ICollection<ILayer> container, IProgressHandler progressHandler)
{
if (File.Exists(fileName) == false) return null;
ILayerManager dm = LayerManager.DefaultLayerManager;
return dm.OpenLayer(fileName, inRam, container, progressHandler);
}
#endregion Static Methods
/// <summary>
/// Gets or sets a boolean indicating whether the memory objects have already been disposed of.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDisposed
{
get { return _isDisposed; }
set { _isDisposed = value; }
}
#region ILayer Members
/// <summary>
/// This is overriden in sub-classes
/// </summary>
/// <param name="affectedArea"></param>
/// <returns></returns>
public virtual bool ClearSelection(out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// This is overriden in sub-classes
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
/// <param name="mode"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public virtual bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// This is overriden in sub-classes
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
/// <param name="mode"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public virtual bool InvertSelection(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// This is overriden in sub-classes
/// </summary>
/// <param name="tolerant">The geographic envelope in cases like cliking near points where tolerance is allowed</param>
/// <param name="strict">The geographic region when working with absolutes, without a tolerance</param>
/// <param name="mode"></param>
/// <param name="affectedArea"></param>
/// <returns></returns>
public virtual bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea)
{
affectedArea = null;
return false;
}
/// <summary>
/// Gets or sets the boolean that controls whether or not items from the layer can be selected
/// </summary>
[Serialize("SelectionEnabled")]
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool SelectionEnabled
{
get
{
return _selectionEnabled;
}
set
{
_selectionEnabled = value;
}
}
/// <summary>
/// Disposes the memory objects in this layer.
/// </summary>
public void Dispose()
{
// This is a new feature, so may be buggy if someone is calling dispose without checking the lock.
// This will help find those spots in debug mode but will cross fingers and hope for the best
// in release mode rather than throwing an exception.
Debug.Assert(IsDisposeLocked == false);
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Locks dispose. This typically adds one instance of an internal reference counter.
/// </summary>
public void LockDispose()
{
_disposeLockCount++;
}
/// <summary>
/// Gets a value indicating whether an existing reference is requesting that the object is not disposed of.
/// Automatic disposal, as is the case when a layer is removed from the map, will not take place until
/// all the locks on dispose have been removed.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsDisposeLocked
{
get { return _disposeLockCount > 0; }
}
/// <summary>
/// Unlocks dispose. This typically removes one instance of an internal reference counter.
/// </summary>
public void UnlockDispose()
{
_disposeLockCount--;
}
/// <summary>
/// Gets a Boolean indicating if this layer can be reprojected.
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanReproject
{
get
{
if (DataSet != null) return DataSet.CanReproject;
return false;
}
}
/// <summary>
/// Gets the or sets the projection information for the dataset of this layer.
/// This only defines the projection information and does not reproject the dataset or the layer.
/// </summary>
[Category("DataSet Properties"), Description("The geographic projection that this raster is using.")]
public ProjectionInfo Projection
{
get
{
if (DataSet != null) return DataSet.Projection;
return _projection;
}
set
{
var current = Projection;
if (current == value) return;
if (DataSet != null)
{
DataSet.Projection = value;
}
_projection = value;
}
}
/// <summary>
/// Gets or sets the unmodified projection string that can be used regardless of whether the
/// DotSpatial.Projection module is available. This string can be in the Proj4string or in the
/// EsriString format. Setting the Projection string only defines projection information.
/// Call the Reproject() method to actually reproject the dataset and layer.
/// </summary>
[Category("DataSet Properties"), Description("The geographic projection that this raster is using.")]
public string ProjectionString
{
get
{
if (DataSet != null) return DataSet.ProjectionString;
return _projectionString;
}
set
{
var current = ProjectionString;
if (current == value) return;
if (DataSet != null)
{
DataSet.ProjectionString = value;
}
_projectionString = value;
var test = ProjectionInfo.FromProj4String(value);
if (!test.IsValid)
{
test.TryParseEsriString(value);
}
if (test.IsValid) Projection = test;
}
}
/// <summary>
/// Reprojects the dataset for this layer.
/// </summary>
/// <param name="targetProjection">The target projection to use.</param>
public virtual void Reproject(ProjectionInfo targetProjection)
{
if (DataSet != null)
{
if (ProgressHandler != null) ProgressHandler.Progress(String.Empty, 0, "Reprojecting Layer " + LegendText);
DataSet.Reproject(targetProjection);
if (ProgressHandler != null) ProgressHandler.Progress(String.Empty, 0, String.Empty);
}
}
#endregion
/// <summary>
/// Fires the SelectionChanged event
/// </summary>
protected virtual void OnSelectionChanged()
{
var h = SelectionChanged;
if (h != null) h(this, EventArgs.Empty);
}
/// <summary>
/// Finalizes an instance of the Layer class.
/// </summary>
~Layer()
{
Dispose(false);
}
/// <summary>
/// This allows overriding layers to handle any memory cleanup.
/// </summary>
/// <param name="disposeManagedResources">True if managed resources should be set to null.</param>
protected virtual void Dispose(bool disposeManagedResources)
{
if (_isDisposed) return;
if (disposeManagedResources)
{
DataSet = null;
var h = Disposed;
if (h != null) h(this, EventArgs.Empty);
}
_isDisposed = true;
}
}
}
| |
//
// System.Net.WebHeaderCollection
//
// Authors:
// Lawrence Pit (loz@cable.a2000.nl)
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Miguel de Icaza (miguel@novell.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2003 Ximian, Inc. (http://www.ximian.com)
// Copyright 2007 Novell, Inc. (http://www.novell.com)
// Copyright (C) 2011 Xamarin Inc (http://www.xamarin.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Text;
// See RFC 2068 par 4.2 Message Headers
namespace Mono.Upnp.Http
{
#if MOONLIGHT
internal class WebHeaderCollection : NameValueCollection, ISerializable {
#else
[Serializable]
[ComVisible(true)]
class WebHeaderCollection : NameValueCollection, ISerializable {
#endif
[Flags]
internal enum HeaderInfo
{
Request = 1,
Response = 1 << 1,
MultiValue = 1 << 10
}
static readonly bool[] allowed_chars = {
false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, false, false, false, false, false, false, false, false, false,
false, false, false, false, false, true, false, true, true, true, true, false, false, false, true,
true, false, true, true, false, true, true, true, true, true, true, true, true, true, true, false,
false, false, false, false, false, false, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true,
true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
false, true, false
};
static readonly Dictionary<string, HeaderInfo> headers;
HeaderInfo? headerRestriction;
HeaderInfo? headerConsistency;
static WebHeaderCollection ()
{
headers = new Dictionary<string, HeaderInfo> (StringComparer.OrdinalIgnoreCase) {
{ "Allow", HeaderInfo.MultiValue },
{ "Accept", HeaderInfo.Request | HeaderInfo.MultiValue },
{ "Accept-Charset", HeaderInfo.MultiValue },
{ "Accept-Encoding", HeaderInfo.MultiValue },
{ "Accept-Language", HeaderInfo.MultiValue },
{ "Accept-Ranges", HeaderInfo.MultiValue },
{ "Authorization", HeaderInfo.MultiValue },
{ "Cache-Control", HeaderInfo.MultiValue },
{ "Cookie", HeaderInfo.MultiValue },
{ "Connection", HeaderInfo.Request | HeaderInfo.MultiValue },
{ "Content-Encoding", HeaderInfo.MultiValue },
{ "Content-Length", HeaderInfo.Request | HeaderInfo.Response },
{ "Content-Type", HeaderInfo.Request },
{ "Content-Language", HeaderInfo.MultiValue },
{ "Date", HeaderInfo.Request },
{ "Expect", HeaderInfo.Request | HeaderInfo.MultiValue},
{ "Host", HeaderInfo.Request },
{ "If-Match", HeaderInfo.MultiValue },
{ "If-Modified-Since", HeaderInfo.Request },
{ "If-None-Match", HeaderInfo.MultiValue },
{ "Keep-Alive", HeaderInfo.Response },
{ "Pragma", HeaderInfo.MultiValue },
{ "Proxy-Authenticate", HeaderInfo.MultiValue },
{ "Proxy-Authorization", HeaderInfo.MultiValue },
{ "Proxy-Connection", HeaderInfo.Request | HeaderInfo.MultiValue },
{ "Range", HeaderInfo.Request | HeaderInfo.MultiValue },
{ "Referer", HeaderInfo.Request },
{ "Set-Cookie", HeaderInfo.MultiValue },
{ "Set-Cookie2", HeaderInfo.MultiValue },
{ "TE", HeaderInfo.MultiValue },
{ "Trailer", HeaderInfo.MultiValue },
{ "Transfer-Encoding", HeaderInfo.Request | HeaderInfo.Response | HeaderInfo.MultiValue },
{ "Upgrade", HeaderInfo.MultiValue },
{ "User-Agent", HeaderInfo.Request },
{ "Vary", HeaderInfo.MultiValue },
{ "Via", HeaderInfo.MultiValue },
{ "Warning", HeaderInfo.MultiValue },
{ "WWW-Authenticate", HeaderInfo.Response | HeaderInfo. MultiValue }
};
}
// Constructors
public WebHeaderCollection ()
{
}
protected WebHeaderCollection (SerializationInfo serializationInfo,
StreamingContext streamingContext)
{
int count;
try {
count = serializationInfo.GetInt32("Count");
for (int i = 0; i < count; i++)
this.Add (serializationInfo.GetString (i.ToString ()),
serializationInfo.GetString ((count + i).ToString ()));
} catch (SerializationException){
count = serializationInfo.GetInt32("count");
for (int i = 0; i < count; i++)
this.Add (serializationInfo.GetString ("k" + i),
serializationInfo.GetString ("v" + i));
}
}
internal WebHeaderCollection (HeaderInfo headerRestriction)
{
this.headerRestriction = headerRestriction;
}
// Methods
public void Add (string header)
{
if (header == null)
throw new ArgumentNullException ("header");
int pos = header.IndexOf (':');
if (pos == -1)
throw new ArgumentException ("no colon found", "header");
this.Add (header.Substring (0, pos), header.Substring (pos + 1));
}
public override void Add (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
CheckRestrictedHeader (name);
this.AddWithoutValidate (name, value);
}
protected void AddWithoutValidate (string headerName, string headerValue)
{
if (!IsHeaderName (headerName))
throw new ArgumentException ("invalid header name: " + headerName, "headerName");
if (headerValue == null)
headerValue = String.Empty;
else
headerValue = headerValue.Trim ();
if (!IsHeaderValue (headerValue))
throw new ArgumentException ("invalid header value: " + headerValue, "headerValue");
AddValue (headerName, headerValue);
}
internal void AddValue (string headerName, string headerValue)
{
base.Add (headerName, headerValue);
}
internal string [] GetValues_internal (string header, bool split)
{
if (header == null)
throw new ArgumentNullException ("header");
string [] values = base.GetValues (header);
if (values == null || values.Length == 0)
return null;
if (split && IsMultiValue (header)) {
List<string> separated = null;
foreach (var value in values) {
if (value.IndexOf (',') < 0)
continue;
if (separated == null) {
separated = new List<string> (values.Length + 1);
foreach (var v in values) {
if (v == value)
break;
separated.Add (v);
}
}
var slices = value.Split (',');
var slices_length = slices.Length;
if (value[value.Length - 1] == ',')
--slices_length;
for (int i = 0; i < slices_length; ++i ) {
separated.Add (slices[i].Trim ());
}
}
if (separated != null)
return separated.ToArray ();
}
return values;
}
public override string [] GetValues (string header)
{
return GetValues_internal (header, true);
}
public override string[] GetValues (int index)
{
string[] values = base.GetValues (index);
if (values == null || values.Length == 0) {
return null;
}
return values;
}
public static bool IsRestricted (string headerName)
{
return IsRestricted (headerName, false);
}
public static bool IsRestricted (string headerName, bool response)
{
if (headerName == null)
throw new ArgumentNullException ("headerName");
if (headerName.Length == 0)
throw new ArgumentException ("empty string", "headerName");
if (!IsHeaderName (headerName))
throw new ArgumentException ("Invalid character in header");
HeaderInfo info;
if (!headers.TryGetValue (headerName, out info))
return false;
var flag = response ? HeaderInfo.Response : HeaderInfo.Request;
return (info & flag) != 0;
}
public override void OnDeserialization (object sender)
{
}
public override void Remove (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
CheckRestrictedHeader (name);
base.Remove (name);
}
public override void Set (string name, string value)
{
if (name == null)
throw new ArgumentNullException ("name");
if (!IsHeaderName (name))
throw new ArgumentException ("invalid header name");
if (value == null)
value = String.Empty;
else
value = value.Trim ();
if (!IsHeaderValue (value))
throw new ArgumentException ("invalid header value");
CheckRestrictedHeader (name);
base.Set (name, value);
}
public byte[] ToByteArray ()
{
return Encoding.UTF8.GetBytes(ToString ());
}
internal string ToStringMultiValue ()
{
StringBuilder sb = new StringBuilder();
int count = base.Count;
for (int i = 0; i < count ; i++) {
string key = GetKey (i);
if (IsMultiValue (key)) {
foreach (string v in GetValues (i)) {
sb.Append (key)
.Append (": ")
.Append (v)
.Append ("\r\n");
}
} else {
sb.Append (key)
.Append (": ")
.Append (Get (i))
.Append ("\r\n");
}
}
return sb.Append("\r\n").ToString();
}
public override string ToString ()
{
StringBuilder sb = new StringBuilder();
int count = base.Count;
for (int i = 0; i < count ; i++)
sb.Append (GetKey (i))
.Append (": ")
.Append (Get (i))
.Append ("\r\n");
return sb.Append("\r\n").ToString();
}
#if !TARGET_JVM
void ISerializable.GetObjectData (SerializationInfo serializationInfo,
StreamingContext streamingContext)
{
GetObjectData (serializationInfo, streamingContext);
}
#endif
public override void GetObjectData (SerializationInfo serializationInfo, StreamingContext streamingContext)
{
int count = base.Count;
serializationInfo.AddValue ("Count", count);
for (int i = 0; i < count; i++) {
serializationInfo.AddValue (i.ToString (), GetKey (i));
serializationInfo.AddValue ((count + i).ToString (), Get (i));
}
}
public override string[] AllKeys {
get {
return base.AllKeys;
}
}
public override int Count {
get {
return base.Count;
}
}
public override KeysCollection Keys {
get {
return base.Keys;
}
}
public override string Get (int index)
{
return base.Get (index);
}
public override string Get (string name)
{
return base.Get (name);
}
public override string GetKey (int index)
{
return base.GetKey (index);
}
public void Add (HttpRequestHeader header, string value)
{
Add (RequestHeaderToString (header), value);
}
public void Remove (HttpRequestHeader header)
{
Remove (RequestHeaderToString (header));
}
public void Set (HttpRequestHeader header, string value)
{
Set (RequestHeaderToString (header), value);
}
public void Add (HttpResponseHeader header, string value)
{
Add (ResponseHeaderToString (header), value);
}
public void Remove (HttpResponseHeader header)
{
Remove (ResponseHeaderToString (header));
}
public void Set (HttpResponseHeader header, string value)
{
Set (ResponseHeaderToString (header), value);
}
public string this [HttpRequestHeader header] {
get {
return Get (RequestHeaderToString (header));
}
set {
Set (header, value);
}
}
public string this [HttpResponseHeader header] {
get {
return Get (ResponseHeaderToString (header));
}
set {
Set (header, value);
}
}
public override void Clear ()
{
base.Clear ();
}
public override IEnumerator GetEnumerator ()
{
return base.GetEnumerator ();
}
// Internal Methods
// With this we don't check for invalid characters in header. See bug #55994.
internal void SetInternal (string header)
{
int pos = header.IndexOf (':');
if (pos == -1)
throw new ArgumentException ("no colon found", "header");
SetInternal (header.Substring (0, pos), header.Substring (pos + 1));
}
internal void SetInternal (string name, string value)
{
if (value == null)
value = String.Empty;
else
value = value.Trim ();
if (!IsHeaderValue (value))
throw new ArgumentException ("invalid header value");
if (IsMultiValue (name)) {
base.Add (name, value);
} else {
base.Remove (name);
base.Set (name, value);
}
}
internal void RemoveAndAdd (string name, string value)
{
if (value == null)
value = String.Empty;
else
value = value.Trim ();
base.Remove (name);
base.Set (name, value);
}
internal void RemoveInternal (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
base.Remove (name);
}
// Private Methods
string RequestHeaderToString (HttpRequestHeader value)
{
CheckHeaderConsistency (HeaderInfo.Request);
switch (value) {
case HttpRequestHeader.CacheControl:
return "Cache-Control";
case HttpRequestHeader.Connection:
return "Connection";
case HttpRequestHeader.Date:
return "Date";
case HttpRequestHeader.KeepAlive:
return "Keep-Alive";
case HttpRequestHeader.Pragma:
return "Pragma";
case HttpRequestHeader.Trailer:
return "Trailer";
case HttpRequestHeader.TransferEncoding:
return "Transfer-Encoding";
case HttpRequestHeader.Upgrade:
return "Upgrade";
case HttpRequestHeader.Via:
return "Via";
case HttpRequestHeader.Warning:
return "Warning";
case HttpRequestHeader.Allow:
return "Allow";
case HttpRequestHeader.ContentLength:
return "Content-Length";
case HttpRequestHeader.ContentType:
return "Content-Type";
case HttpRequestHeader.ContentEncoding:
return "Content-Encoding";
case HttpRequestHeader.ContentLanguage:
return "Content-Language";
case HttpRequestHeader.ContentLocation:
return "Content-Location";
case HttpRequestHeader.ContentMd5:
return "Content-MD5";
case HttpRequestHeader.ContentRange:
return "Content-Range";
case HttpRequestHeader.Expires:
return "Expires";
case HttpRequestHeader.LastModified:
return "Last-Modified";
case HttpRequestHeader.Accept:
return "Accept";
case HttpRequestHeader.AcceptCharset:
return "Accept-Charset";
case HttpRequestHeader.AcceptEncoding:
return "Accept-Encoding";
case HttpRequestHeader.AcceptLanguage:
return "accept-language";
case HttpRequestHeader.Authorization:
return "Authorization";
case HttpRequestHeader.Cookie:
return "Cookie";
case HttpRequestHeader.Expect:
return "Expect";
case HttpRequestHeader.From:
return "From";
case HttpRequestHeader.Host:
return "Host";
case HttpRequestHeader.IfMatch:
return "If-Match";
case HttpRequestHeader.IfModifiedSince:
return "If-Modified-Since";
case HttpRequestHeader.IfNoneMatch:
return "If-None-Match";
case HttpRequestHeader.IfRange:
return "If-Range";
case HttpRequestHeader.IfUnmodifiedSince:
return "If-Unmodified-Since";
case HttpRequestHeader.MaxForwards:
return "Max-Forwards";
case HttpRequestHeader.ProxyAuthorization:
return "Proxy-Authorization";
case HttpRequestHeader.Referer:
return "Referer";
case HttpRequestHeader.Range:
return "Range";
case HttpRequestHeader.Te:
return "TE";
case HttpRequestHeader.Translate:
return "Translate";
case HttpRequestHeader.UserAgent:
return "User-Agent";
default:
throw new InvalidOperationException ();
}
}
string ResponseHeaderToString (HttpResponseHeader value)
{
CheckHeaderConsistency (HeaderInfo.Response);
switch (value) {
case HttpResponseHeader.CacheControl:
return "Cache-Control";
case HttpResponseHeader.Connection:
return "Connection";
case HttpResponseHeader.Date:
return "Date";
case HttpResponseHeader.KeepAlive:
return "Keep-Alive";
case HttpResponseHeader.Pragma:
return "Pragma";
case HttpResponseHeader.Trailer:
return "Trailer";
case HttpResponseHeader.TransferEncoding:
return "Transfer-Encoding";
case HttpResponseHeader.Upgrade:
return "Upgrade";
case HttpResponseHeader.Via:
return "Via";
case HttpResponseHeader.Warning:
return "Warning";
case HttpResponseHeader.Allow:
return "Allow";
case HttpResponseHeader.ContentLength:
return "Content-Length";
case HttpResponseHeader.ContentType:
return "Content-Type";
case HttpResponseHeader.ContentEncoding:
return "Content-Encoding";
case HttpResponseHeader.ContentLanguage:
return "Content-Language";
case HttpResponseHeader.ContentLocation:
return "Content-Location";
case HttpResponseHeader.ContentMd5:
return "Content-MD5";
case HttpResponseHeader.ContentRange:
return "Content-Range";
case HttpResponseHeader.Expires:
return "Expires";
case HttpResponseHeader.LastModified:
return "Last-Modified";
case HttpResponseHeader.AcceptRanges:
return "Accept-Ranges";
case HttpResponseHeader.Age:
return "Age";
case HttpResponseHeader.ETag:
return "ETag";
case HttpResponseHeader.Location:
return "Location";
case HttpResponseHeader.ProxyAuthenticate:
return "Proxy-Authenticate";
case HttpResponseHeader.RetryAfter:
return "Retry-After";
case HttpResponseHeader.Server:
return "Server";
case HttpResponseHeader.SetCookie:
return "Set-Cookie";
case HttpResponseHeader.Vary:
return "Vary";
case HttpResponseHeader.WwwAuthenticate:
return "WWW-Authenticate";
default:
throw new InvalidOperationException ();
}
}
void CheckRestrictedHeader (string headerName)
{
if (!headerRestriction.HasValue)
return;
HeaderInfo info;
if (!headers.TryGetValue (headerName, out info))
return;
if ((info & headerRestriction.Value) != 0)
throw new ArgumentException ("This header must be modified with the appropiate property.");
}
void CheckHeaderConsistency (HeaderInfo value)
{
if (!headerConsistency.HasValue) {
headerConsistency = value;
return;
}
if ((headerConsistency & value) == 0)
throw new InvalidOperationException ();
}
internal static bool IsMultiValue (string headerName)
{
if (headerName == null)
return false;
HeaderInfo info;
return headers.TryGetValue (headerName, out info) && (info & HeaderInfo.MultiValue) != 0;
}
internal static bool IsHeaderValue (string value)
{
// TEXT any 8 bit value except CTL's (0-31 and 127)
// but including \r\n space and \t
// after a newline at least one space or \t must follow
// certain header fields allow comments ()
int len = value.Length;
for (int i = 0; i < len; i++) {
char c = value [i];
if (c == 127)
return false;
if (c < 0x20 && (c != '\r' && c != '\n' && c != '\t'))
return false;
if (c == '\n' && ++i < len) {
c = value [i];
if (c != ' ' && c != '\t')
return false;
}
}
return true;
}
internal static bool IsHeaderName (string name)
{
if (name == null || name.Length == 0)
return false;
int len = name.Length;
for (int i = 0; i < len; i++) {
char c = name [i];
if (c > 126 || !allowed_chars [c])
return false;
}
return true;
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Cassandra.DataStax.Graph;
using Cassandra.Tests.Requests;
using Cassandra.Tests.TestHelpers;
using Moq;
using NUnit.Framework;
using System;
using Cassandra.Tests.Connections.TestHelpers;
namespace Cassandra.Tests.DataStax.Graph
{
public class ExecuteGraphTests : BaseUnitTest
{
private ICluster _cluster;
private static ISession NewInstance(ICluster cluster)
{
return cluster.Connect();
}
[TearDown]
public void TearDown()
{
_cluster?.Dispose();
_cluster = null;
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_SimpleStatement()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.NotNull(coreStatement);
Assert.Null(coreStatement.Timestamp);
Assert.Null(coreStatement.ConsistencyLevel);
Assert.AreEqual("g.V()", coreStatement.QueryString);
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_Timestamp_Set()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
var timestamp = DateTimeOffset.Now;
session.ExecuteGraph(new SimpleGraphStatement("g.V()").SetTimestamp(timestamp));
Assert.NotNull(coreStatement);
Assert.Null(coreStatement.ConsistencyLevel);
Assert.AreEqual(coreStatement.Timestamp, timestamp);
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_ConsistencyLevel_Set()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
const ConsistencyLevel consistency = ConsistencyLevel.Three;
session.ExecuteGraph(new SimpleGraphStatement("g.V()").SetConsistencyLevel(consistency));
Assert.NotNull(coreStatement);
Assert.AreEqual(coreStatement.ConsistencyLevel, consistency);
Assert.Null(coreStatement.Timestamp);
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_ReadTimeout_Set_To_Default()
{
const int readTimeout = 5000;
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt, new GraphOptions().SetReadTimeoutMillis(readTimeout));
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.NotNull(coreStatement);
Assert.AreEqual(readTimeout, coreStatement.ReadTimeoutMillis);
//Another one with the statement level timeout set to zero
session.ExecuteGraph(new SimpleGraphStatement("g.V()").SetReadTimeoutMillis(0));
Assert.NotNull(coreStatement);
Assert.AreEqual(readTimeout, coreStatement.ReadTimeoutMillis);
Assert.True(coreStatement.OutgoingPayload.ContainsKey("request-timeout"));
Assert.That(coreStatement.OutgoingPayload["request-timeout"], Is.EqualTo(ExecuteGraphTests.ToBuffer(readTimeout)));
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_ReadTimeout_Set_From_Statement()
{
const int defaultReadTimeout = 15000;
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt, new GraphOptions().SetReadTimeoutMillis(defaultReadTimeout));
var session = _cluster.Connect();
const int readTimeout = 6000;
session.ExecuteGraph(new SimpleGraphStatement("g.V()").SetReadTimeoutMillis(readTimeout));
Assert.NotNull(coreStatement);
Assert.AreEqual(readTimeout, coreStatement.ReadTimeoutMillis);
Assert.True(coreStatement.OutgoingPayload.ContainsKey("request-timeout"));
Assert.That(coreStatement.OutgoingPayload["request-timeout"], Is.EqualTo(ExecuteGraphTests.ToBuffer(readTimeout)));
}
[Test]
public void ExecuteGraph_Should_Call_ExecuteAsync_With_Dictionary_Parameters_Set()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
var parameters = new Dictionary<string, object>
{
{ "myName", "is what"}
};
session.ExecuteGraph(new SimpleGraphStatement(parameters, "g.V().has('name', myName)"));
Assert.NotNull(coreStatement);
Assert.AreEqual("g.V().has('name', myName)", coreStatement.QueryString);
//A single parameter with the key/values json stringified
Assert.AreEqual(new object[] { "{\"myName\":\"is what\"}" }, coreStatement.QueryValues);
}
[Test]
public void ExecuteGraph_Should_Wrap_RowSet()
{
var rowMock1 = new Mock<Row>();
rowMock1.Setup(r => r.GetValue<string>(It.Is<string>(n => n == "gremlin"))).Returns("{\"result\": 100}");
var rowMock2 = new Mock<Row>();
rowMock2.Setup(r => r.GetValue<string>(It.Is<string>(n => n == "gremlin"))).Returns("{\"result\": 101}");
IEnumerable<Row> rows = new[]
{
rowMock1.Object,
rowMock2.Object
};
var rsMock = new Mock<RowSet>();
rsMock.Setup(r => r.GetEnumerator()).Returns(() => rows.GetEnumerator());
_cluster = ExecuteGraphTests.GetCluster(stmt => { }, null, rsMock.Object);
var session = _cluster.Connect();
var rsGraph = session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.NotNull(rsGraph);
var resultArray = rsGraph.ToArray();
Assert.AreEqual(2, resultArray.Length);
CollectionAssert.AreEqual(new[] { 100, 101 }, resultArray.Select(g => g.ToInt32()));
}
[Test]
public void ExecuteGraph_Should_Build_Payload_With_Default_Values()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.NotNull(coreStatement);
Assert.NotNull(coreStatement.OutgoingPayload);
//The default graph payload
Assert.AreEqual(3, coreStatement.OutgoingPayload.Count);
CollectionAssert.AreEqual(new[] { "graph-language", "graph-source", "graph-results" }, coreStatement.OutgoingPayload.Keys);
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-results"]), "graphson-1.0");
}
[Test]
public void ExecuteGraph_Should_Build_Payload_With_GraphOptions()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(
stmt => coreStatement = stmt,
new GraphOptions()
.SetName("name1")
.SetSource("My source!")
.SetReadTimeoutMillis(22222)
.SetReadConsistencyLevel(ConsistencyLevel.LocalQuorum)
.SetWriteConsistencyLevel(ConsistencyLevel.EachQuorum)
.SetGraphProtocolVersion(GraphProtocol.GraphSON2));
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.NotNull(coreStatement);
Assert.NotNull(coreStatement.OutgoingPayload);
Assert.That(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-source"]), Is.EqualTo("My source!"));
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-name"]), "name1");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-read-consistency"]), "LOCAL_QUORUM");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-write-consistency"]), "EACH_QUORUM");
//default
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-language"]), "gremlin-groovy");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-results"]), "graphson-2.0");
Assert.That(coreStatement.OutgoingPayload["request-timeout"], Is.EqualTo(ExecuteGraphTests.ToBuffer(22222)));
}
[Test]
public void ExecuteGraph_Should_Build_Payload_With_Statement_Properties()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(
stmt => coreStatement = stmt,
new GraphOptions()
.SetName("name1")
.SetSource("My source!")
.SetReadConsistencyLevel(ConsistencyLevel.LocalQuorum)
.SetWriteConsistencyLevel(ConsistencyLevel.EachQuorum)
.SetGraphProtocolVersion(GraphProtocol.GraphSON2));
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()")
.SetGraphLanguage("my-lang")
.SetReadTimeoutMillis(5555)
.SetSystemQuery()
.SetGraphReadConsistencyLevel(ConsistencyLevel.Two)
.SetGraphSource("Statement source")
.SetGraphProtocolVersion(GraphProtocol.GraphSON3));
Assert.NotNull(coreStatement);
Assert.NotNull(coreStatement.OutgoingPayload);
Assert.That(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-source"]), Is.EqualTo("Statement source"));
//is a system query
Assert.False(coreStatement.OutgoingPayload.ContainsKey("graph-name"));
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-read-consistency"]), "TWO");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-write-consistency"]), "EACH_QUORUM");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-language"]), "my-lang");
Assert.AreEqual(Encoding.UTF8.GetString(coreStatement.OutgoingPayload["graph-results"]), "graphson-3.0");
Assert.That(coreStatement.OutgoingPayload["request-timeout"], Is.EqualTo(ExecuteGraphTests.ToBuffer(5555)));
}
[Test]
public void ExecuteGraph_Should_Allow_GraphNode_As_Parameters()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
const string expectedJson =
"{\"member_id\":123,\"community_id\":586910,\"~label\":\"vertex\",\"group_id\":2}";
var id = new GraphNode("{\"result\":" + expectedJson + "}");
session.ExecuteGraph(new SimpleGraphStatement("g.V(vertexId)", new { vertexId = id }));
Assert.NotNull(coreStatement);
Assert.AreEqual(1, coreStatement.QueryValues.Length);
Assert.AreEqual("{\"vertexId\":" + expectedJson + "}", coreStatement.QueryValues[0]);
}
[Test]
public void ExecuteGraph_Should_Allow_BigInteger_As_Parameters()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
var value = BigInteger.Parse("1234567890123456789123456789");
session.ExecuteGraph(new SimpleGraphStatement("g.V(vertexId)", new { value }));
Assert.NotNull(coreStatement);
Assert.AreEqual(1, coreStatement.QueryValues.Length);
Assert.AreEqual("{\"value\":" + value + "}", coreStatement.QueryValues[0]);
}
[Test]
public void ExecuteGraph_Should_Allow_IpAddress_As_Parameters()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt);
var session = _cluster.Connect();
var value = IPAddress.Parse("192.168.1.100");
session.ExecuteGraph(new SimpleGraphStatement("g.V(vertexId)", new { value }));
Assert.NotNull(coreStatement);
Assert.AreEqual(1, coreStatement.QueryValues.Length);
Assert.AreEqual("{\"value\":\"" + value + "\"}", coreStatement.QueryValues[0]);
}
[Test]
public void Should_Make_Rpc_Call_When_Using_Analytics_Source()
{
var coreStatements = new List<SimpleStatement>();
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatements.Add(stmt), null, stmt =>
{
if (stmt is SimpleStatement st && st.QueryString.StartsWith("CALL "))
{
var rowMock = new Mock<Row>();
rowMock
.Setup(r => r.GetValue<IDictionary<string, string>>(It.Is<string>(c => c == "result")))
.Returns(new Dictionary<string, string> { { "location", "1.2.3.4:8888" } });
var rows = new[]
{
rowMock.Object
};
var mock = new Mock<RowSet>();
mock
.Setup(r => r.GetEnumerator()).Returns(() => ((IEnumerable<Row>)rows).GetEnumerator());
return mock.Object;
}
return new RowSet();
});
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()").SetGraphSourceAnalytics());
Assert.AreEqual(2, coreStatements.Count);
Assert.AreEqual("CALL DseClientTool.getAnalyticsGraphServer()", coreStatements[0].QueryString);
Assert.AreEqual("g.V()", coreStatements[1].QueryString);
var targettedStatement = coreStatements[1] as TargettedSimpleStatement;
Assert.NotNull(targettedStatement);
Assert.NotNull(targettedStatement.PreferredHost);
Assert.AreEqual("1.2.3.4:9042", targettedStatement.PreferredHost.Address.ToString());
}
[Test]
public void Should_Not_Make_Rpc_Calls_When_Using_Other_Sources()
{
var coreStatements = new List<SimpleStatement>();
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatements.Add(stmt));
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()"));
Assert.AreEqual(1, coreStatements.Count);
Assert.AreEqual("g.V()", coreStatements[0].QueryString);
var targettedStatement = coreStatements[0] as TargettedSimpleStatement;
Assert.NotNull(targettedStatement);
Assert.Null(targettedStatement.PreferredHost);
}
[Test]
public void Should_Identity_Timeout_Infinite_ReadTimeout()
{
SimpleStatement coreStatement = null;
_cluster = ExecuteGraphTests.GetCluster(stmt => coreStatement = stmt, new GraphOptions().SetReadTimeoutMillis(32000));
var session = _cluster.Connect();
session.ExecuteGraph(new SimpleGraphStatement("g.V()")
.SetReadTimeoutMillis(Timeout.Infinite));
Assert.NotNull(coreStatement);
Assert.NotNull(coreStatement.OutgoingPayload);
Assert.False(coreStatement.OutgoingPayload.ContainsKey("request-timeout"));
Assert.That(coreStatement.ReadTimeoutMillis, Is.EqualTo(int.MaxValue));
}
[Test]
public async Task Should_Consider_Bulk_In_Gremlin_Response_With_GraphSON1()
{
var rs = ExecuteGraphTests.GetRowSet(ExecuteGraphTests.GetGremlin(1, 1), ExecuteGraphTests.GetGremlin(2, 2), ExecuteGraphTests.GetGremlin(3, 3), ExecuteGraphTests.GetGremlin(4));
_cluster = ExecuteGraphTests.GetCluster(stmt => { }, null, rs);
var session = _cluster.Connect();
var graphStatement = new SimpleGraphStatement("g.V()").SetGraphLanguage(GraphOptions.DefaultLanguage);
var result = await session.ExecuteGraphAsync(graphStatement).ConfigureAwait(false);
Assert.That(result.To<int>(), Is.EquivalentTo(new[] { 1, 2, 2, 3, 3, 3, 4 }));
}
[Test]
public async Task Should_Consider_Bulk_In_Gremlin_Response_With_GraphSON2()
{
var rs = ExecuteGraphTests.GetRowSet(ExecuteGraphTests.GetGremlin(1),
ExecuteGraphTests.GetGremlin(2, "{\"@type\": \"g:Int64\", \"@value\": 2}"),
ExecuteGraphTests.GetGremlin(3, "{\"@type\": \"g:Int64\", \"@value\": 3}"),
ExecuteGraphTests.GetGremlin(10, "{\"@type\": \"g:Int64\", \"@value\": 1}"));
_cluster = ExecuteGraphTests.GetCluster(stmt => { }, null, rs);
var session = _cluster.Connect();
var graphStatement = new SimpleGraphStatement("g.V()").SetGraphLanguage(GraphOptions.BytecodeJson);
var result = await session.ExecuteGraphAsync(graphStatement).ConfigureAwait(false);
Assert.That(result.To<long>(), Is.EquivalentTo(new[] { 1, 2, 2, 3, 3, 3, 10 }));
}
private static byte[] ToBuffer(long value)
{
return Serialization.TypeSerializer.PrimitiveLongSerializer.Serialize(4, value);
}
private static ICluster GetCluster(
Action<SimpleStatement> executeCallback, GraphOptions graphOptions = null, RowSet rs = null)
{
return ExecuteGraphTests.GetCluster(executeCallback, graphOptions, stmt => rs ?? new RowSet());
}
private static ICluster GetCluster(
Action<SimpleStatement> executeCallback, GraphOptions graphOptions, Func<IStatement, RowSet> rs)
{
var config = new TestConfigurationBuilder
{
GraphOptions = graphOptions ?? new GraphOptions(),
ControlConnectionFactory = new FakeControlConnectionFactory(),
ConnectionFactory = new FakeConnectionFactory(),
RequestHandlerFactory = new FakeRequestHandlerFactory(stmt => executeCallback((SimpleStatement)stmt), rs)
}.Build();
return Cluster.BuildFrom(
new FakeInitializer(
config,
new List<IPEndPoint>
{
new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042),
new IPEndPoint(IPAddress.Parse("1.2.3.4"), 9042)
}),
new List<string>());
}
private static RowSet GetRowSet(params string[] gremlin)
{
var rows = gremlin.Select(g => new[] { new KeyValuePair<string, object>("gremlin", g) }).ToArray();
return TestHelper.CreateRowSet(rows);
}
private static string GetGremlin(object result, object bulk = null)
{
if (bulk == null)
{
// Simulate bulk property not present
return $"{{\"result\": {result}}}";
}
return $"{{\"result\": {result}, \"bulk\": {bulk}}}";
}
}
}
| |
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using Sqloogle.Libs.NLog.Common;
namespace Sqloogle.Libs.NLog.Internal.FileAppenders
{
/// <summary>
/// Base class for optimized file appenders.
/// </summary>
internal abstract class BaseFileAppender : IDisposable
{
private readonly Random random = new Random();
/// <summary>
/// Initializes a new instance of the <see cref="BaseFileAppender" /> class.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="createParameters">The create parameters.</param>
public BaseFileAppender(string fileName, ICreateFileParameters createParameters)
{
CreateFileParameters = createParameters;
FileName = fileName;
OpenTime = CurrentTimeGetter.Now;
LastWriteTime = DateTime.MinValue;
}
/// <summary>
/// Gets the name of the file.
/// </summary>
/// <value>The name of the file.</value>
public string FileName { get; private set; }
/// <summary>
/// Gets the last write time.
/// </summary>
/// <value>The last write time.</value>
public DateTime LastWriteTime { get; private set; }
/// <summary>
/// Gets the open time of the file.
/// </summary>
/// <value>The open time.</value>
public DateTime OpenTime { get; private set; }
/// <summary>
/// Gets the file creation parameters.
/// </summary>
/// <value>The file creation parameters.</value>
public ICreateFileParameters CreateFileParameters { get; private set; }
/// <summary>
/// Writes the specified bytes.
/// </summary>
/// <param name="bytes">The bytes.</param>
public abstract void Write(byte[] bytes);
/// <summary>
/// Flushes this instance.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this instance.
/// </summary>
public abstract void Close();
/// <summary>
/// Gets the file info.
/// </summary>
/// <param name="lastWriteTime">The last write time.</param>
/// <param name="fileLength">Length of the file.</param>
/// <returns>True if the operation succeeded, false otherwise.</returns>
public abstract bool GetFileInfo(out DateTime lastWriteTime, out long fileLength);
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing">
/// True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.
/// </param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
Close();
}
}
/// <summary>
/// Records the last write time for a file.
/// </summary>
protected void FileTouched()
{
LastWriteTime = CurrentTimeGetter.Now;
}
/// <summary>
/// Records the last write time for a file to be specific date.
/// </summary>
/// <param name="dateTime">Date and time when the last write occurred.</param>
protected void FileTouched(DateTime dateTime)
{
LastWriteTime = dateTime;
}
/// <summary>
/// Creates the file stream.
/// </summary>
/// <param name="allowConcurrentWrite">
/// If set to <c>true</c> allow concurrent writes.
/// </param>
/// <returns>
/// A <see cref="FileStream" /> object which can be used to write to the file.
/// </returns>
protected FileStream CreateFileStream(bool allowConcurrentWrite)
{
var currentDelay = CreateFileParameters.ConcurrentWriteAttemptDelay;
InternalLogger.Trace("Opening {0} with concurrentWrite={1}", FileName, allowConcurrentWrite);
for (var i = 0; i < CreateFileParameters.ConcurrentWriteAttempts; ++i)
{
try
{
try
{
return TryCreateFileStream(allowConcurrentWrite);
}
catch (DirectoryNotFoundException)
{
if (!CreateFileParameters.CreateDirs)
{
throw;
}
Directory.CreateDirectory(Path.GetDirectoryName(FileName));
return TryCreateFileStream(allowConcurrentWrite);
}
}
catch (IOException)
{
if (!CreateFileParameters.ConcurrentWrites || !allowConcurrentWrite || i + 1 == CreateFileParameters.ConcurrentWriteAttempts)
{
throw; // rethrow
}
var actualDelay = random.Next(currentDelay);
InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i, FileName, actualDelay);
currentDelay *= 2;
Thread.Sleep(actualDelay);
}
}
throw new InvalidOperationException("Should not be reached.");
}
#if !NET_CF && !SILVERLIGHT
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")]
private FileStream WindowsCreateFile(string fileName, bool allowConcurrentWrite)
{
var fileShare = Win32FileNativeMethods.FILE_SHARE_READ;
if (allowConcurrentWrite)
{
fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE;
}
if (CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows)
{
fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE;
}
var handle = Win32FileNativeMethods.CreateFile(
fileName,
Win32FileNativeMethods.FileAccess.GenericWrite,
fileShare,
IntPtr.Zero,
Win32FileNativeMethods.CreationDisposition.OpenAlways,
CreateFileParameters.FileAttributes,
IntPtr.Zero);
if (handle.ToInt32() == -1)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
var safeHandle = new SafeFileHandle(handle, true);
var returnValue = new FileStream(safeHandle, FileAccess.Write, CreateFileParameters.BufferSize);
returnValue.Seek(0, SeekOrigin.End);
return returnValue;
}
#endif
private FileStream TryCreateFileStream(bool allowConcurrentWrite)
{
var fileShare = FileShare.Read;
if (allowConcurrentWrite)
{
fileShare = FileShare.ReadWrite;
}
#if !NET_CF
if (CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows)
{
fileShare |= FileShare.Delete;
}
#endif
#if !NET_CF && !SILVERLIGHT
if (PlatformDetector.IsDesktopWin32)
{
return WindowsCreateFile(FileName, allowConcurrentWrite);
}
#endif
return new FileStream(
FileName,
FileMode.Append,
FileAccess.Write,
fileShare,
CreateFileParameters.BufferSize);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32.SafeHandles;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
public static class File
{
public static StreamReader OpenText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalOpen(path);
return new StreamReader(stream);
}
public static StreamWriter CreateText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path);
return new StreamWriter(stream);
}
public static StreamWriter AppendText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path);
return new StreamWriter(stream);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, false);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public static void Copy(String sourceFileName, String destFileName, bool overwrite)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
InternalCopy(sourceFileName, destFileName, overwrite);
}
/// <devdoc>
/// Note: This returns the fully qualified name of the destination file.
/// </devdoc>
[System.Security.SecuritySafeCritical]
internal static String InternalCopy(String sourceFileName, String destFileName, bool overwrite)
{
Contract.Requires(sourceFileName != null);
Contract.Requires(destFileName != null);
Contract.Requires(sourceFileName.Length > 0);
Contract.Requires(destFileName.Length > 0);
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
FileSystem.Current.CopyFile(fullSourceFileName, fullDestFileName, overwrite);
return fullDestFileName;
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path)
{
return Create(path, FileStream.DefaultBufferSize);
}
// Creates a file in a particular path. If the file exists, it is replaced.
// The file is opened with ReadWrite access and cannot be opened by another
// application until it has been closed. An IOException is thrown if the
// directory specified doesn't exist.
//
// Your application must have Create, Read, and Write permissions to
// the file.
//
public static FileStream Create(String path, int bufferSize)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None, bufferSize);
}
public static FileStream Create(String path, int bufferSize, FileOptions options)
{
return new FileStream(path, FileMode.Create, FileAccess.ReadWrite,
FileShare.None, bufferSize, options);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
Contract.EndContractBlock();
String fullPath = Path.GetFullPath(path);
FileSystem.Current.DeleteFile(fullPath);
}
// Tests if a file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false. Note that if path describes a directory,
// Exists will return true.
//
// Your application must have Read permission for the target directory.
//
[System.Security.SecuritySafeCritical]
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
path = Path.GetFullPath(path);
// After normalizing, check whether path ends in directory separator.
// Otherwise, FillAttributeInfo removes it and we may return a false positive.
// GetFullPath should never return null
Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
{
return false;
}
return InternalExists(path);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
[System.Security.SecurityCritical] // auto-generated
internal static bool InternalExists(String path)
{
return FileSystem.Current.FileExists(path);
}
public static FileStream Open(String path, FileMode mode)
{
return Open(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access)
{
return Open(path, mode, access, FileShare.None);
}
public static FileStream Open(String path, FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(path, mode, access, share);
}
internal static DateTimeOffset GetUtcDateTimeOffset(DateTime dateTime)
{
// File and Directory UTC APIs treat a DateTimeKind.Unspecified as UTC whereas
// ToUniversalTime treats this as local.
if (dateTime.Kind == DateTimeKind.Unspecified)
{
return DateTime.SpecifyKind(dateTime, DateTimeKind.Utc);
}
return dateTime.ToUniversalTime();
}
public static void SetCreationTime(String path, DateTime creationTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, creationTimeUtc, asDirectory: false);
}
public static void SetCreationTimeUtc(String path, DateTime creationTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetCreationTime(fullPath, GetUtcDateTimeOffset(creationTime), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetCreationTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetCreationTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetCreationTime(fullPath).UtcDateTime;
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: false);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastAccessTime(fullPath, GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastAccessTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastAccessTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastAccessTime(fullPath).UtcDateTime;
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: false);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetLastWriteTime(fullPath, GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: false);
}
[System.Security.SecuritySafeCritical]
public static DateTime GetLastWriteTime(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).LocalDateTime;
}
[System.Security.SecuritySafeCritical] // auto-generated
public static DateTime GetLastWriteTimeUtc(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetLastWriteTime(fullPath).UtcDateTime;
}
[System.Security.SecuritySafeCritical]
public static FileAttributes GetAttributes(String path)
{
String fullPath = Path.GetFullPath(path);
return FileSystem.Current.GetAttributes(fullPath);
}
[System.Security.SecurityCritical]
public static void SetAttributes(String path, FileAttributes fileAttributes)
{
String fullPath = Path.GetFullPath(path);
FileSystem.Current.SetAttributes(fullPath, fileAttributes);
}
[System.Security.SecuritySafeCritical]
public static FileStream OpenRead(String path)
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(String path)
{
return new FileStream(path, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllText(path, Encoding.UTF8);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static String ReadAllText(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllText(path, encoding);
}
[System.Security.SecurityCritical]
private static String InternalReadAllText(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalOpen(path, useAsync: false);
using (StreamReader sr = new StreamReader(stream, encoding, true))
return sr.ReadToEnd();
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, UTF8NoBOM);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalWriteAllText(path, contents, encoding);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalCreate(path, useAsync: false);
using (StreamWriter sw = new StreamWriter(stream, encoding))
sw.Write(contents);
}
[System.Security.SecuritySafeCritical] // auto-generated
public static byte[] ReadAllBytes(String path)
{
return InternalReadAllBytes(path);
}
[System.Security.SecurityCritical]
private static byte[] InternalReadAllBytes(String path)
{
// bufferSize == 1 used to avoid unnecessary buffer in FileStream
using (FileStream fs = FileStream.InternalOpen(path, bufferSize: 1, useAsync: false))
{
long fileLength = fs.Length;
if (fileLength > Int32.MaxValue)
throw new IOException(SR.IO_FileTooLong2GB);
int index = 0;
int count = (int)fileLength;
byte[] bytes = new byte[count];
while (count > 0)
{
int n = fs.Read(bytes, index, count);
if (n == 0)
throw Error.GetEndOfFile();
index += n;
count -= n;
}
return bytes;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public static void WriteAllBytes(String path, byte[] bytes)
{
if (path == null)
throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
if (bytes == null)
throw new ArgumentNullException(nameof(bytes));
Contract.EndContractBlock();
InternalWriteAllBytes(path, bytes);
}
[System.Security.SecurityCritical]
private static void InternalWriteAllBytes(String path, byte[] bytes)
{
Contract.Requires(path != null);
Contract.Requires(path.Length != 0);
Contract.Requires(bytes != null);
using (FileStream fs = FileStream.InternalCreate(path, useAsync: false))
{
fs.Write(bytes, 0, bytes.Length);
}
}
public static String[] ReadAllLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllLines(path, Encoding.UTF8);
}
public static String[] ReadAllLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return InternalReadAllLines(path, encoding);
}
private static String[] InternalReadAllLines(String path, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length != 0);
String line;
List<String> lines = new List<String>();
Stream stream = FileStream.InternalOpen(path, useAsync: false);
using (StreamReader sr = new StreamReader(stream, encoding))
while ((line = sr.ReadLine()) != null)
lines.Add(line);
return lines.ToArray();
}
public static IEnumerable<String> ReadLines(String path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, Encoding.UTF8);
}
public static IEnumerable<String> ReadLines(String path, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
return ReadLinesIterator.CreateIterator(path, encoding);
}
public static void WriteAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, UTF8NoBOM), contents);
}
public static void WriteAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalCreate(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, encoding), contents);
}
private static void InternalWriteAllLines(TextWriter writer, IEnumerable<String> contents)
{
Contract.Requires(writer != null);
Contract.Requires(contents != null);
using (writer)
{
foreach (String line in contents)
{
writer.WriteLine(line);
}
}
}
public static void AppendAllText(String path, String contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, UTF8NoBOM);
}
public static void AppendAllText(String path, String contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
InternalAppendAllText(path, contents, encoding);
}
private static void InternalAppendAllText(String path, String contents, Encoding encoding)
{
Contract.Requires(path != null);
Contract.Requires(encoding != null);
Contract.Requires(path.Length > 0);
Stream stream = FileStream.InternalAppend(path, useAsync: false);
using (StreamWriter sw = new StreamWriter(stream, encoding))
sw.Write(contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, UTF8NoBOM), contents);
}
public static void AppendAllLines(String path, IEnumerable<String> contents, Encoding encoding)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (contents == null)
throw new ArgumentNullException(nameof(contents));
if (encoding == null)
throw new ArgumentNullException(nameof(encoding));
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, nameof(path));
Contract.EndContractBlock();
Stream stream = FileStream.InternalAppend(path, useAsync: false);
InternalWriteAllLines(new StreamWriter(stream, encoding), contents);
}
// Moves a specified file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public static void Move(String sourceFileName, String destFileName)
{
if (sourceFileName == null)
throw new ArgumentNullException(nameof(sourceFileName), SR.ArgumentNull_FileName);
if (destFileName == null)
throw new ArgumentNullException(nameof(destFileName), SR.ArgumentNull_FileName);
if (sourceFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(sourceFileName));
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destFileName));
Contract.EndContractBlock();
String fullSourceFileName = Path.GetFullPath(sourceFileName);
String fullDestFileName = Path.GetFullPath(destFileName);
if (!InternalExists(fullSourceFileName))
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, fullSourceFileName), fullSourceFileName);
}
FileSystem.Current.MoveFile(fullSourceFileName, fullDestFileName);
}
private static volatile Encoding _UTF8NoBOM;
private static Encoding UTF8NoBOM
{
get
{
if (_UTF8NoBOM == null)
{
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Interlocked.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Core;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders
{
/// <summary>
/// <see cref="IModelBinder"/> implementation for binding complex types.
/// </summary>
public sealed partial class ComplexObjectModelBinder : IModelBinder
{
// Don't want a new public enum because communication between the private and internal methods of this class
// should not be exposed. Can't use an internal enum because types of [TheoryData] values must be public.
// Model contains only properties that are expected to bind from value providers and no value provider has
// matching data.
internal const int NoDataAvailable = 0;
// If model contains properties that are expected to bind from value providers, no value provider has matching
// data. Remaining (greedy) properties might bind successfully.
internal const int GreedyPropertiesMayHaveData = 1;
// Model contains at least one property that is expected to bind from value providers and a value provider has
// matching data.
internal const int ValueProviderDataAvailable = 2;
private readonly IDictionary<ModelMetadata, IModelBinder> _propertyBinders;
private readonly IReadOnlyList<IModelBinder> _parameterBinders;
private readonly ILogger _logger;
private Func<object>? _modelCreator;
internal ComplexObjectModelBinder(
IDictionary<ModelMetadata, IModelBinder> propertyBinders,
IReadOnlyList<IModelBinder> parameterBinders,
ILogger<ComplexObjectModelBinder> logger)
{
_propertyBinders = propertyBinders;
_parameterBinders = parameterBinders;
_logger = logger;
}
/// <inheritdoc/>
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
_logger.AttemptingToBindModel(bindingContext);
var parameterData = CanCreateModel(bindingContext);
if (parameterData == NoDataAvailable)
{
return Task.CompletedTask;
}
// Perf: separated to avoid allocating a state machine when we don't
// need to go async.
return BindModelCoreAsync(bindingContext, parameterData);
}
private async Task BindModelCoreAsync(ModelBindingContext bindingContext, int propertyData)
{
Debug.Assert(propertyData == GreedyPropertiesMayHaveData || propertyData == ValueProviderDataAvailable);
// Create model first (if necessary) to avoid reporting errors about properties when activation fails.
var attemptedBinding = false;
var bindingSucceeded = false;
var modelMetadata = bindingContext.ModelMetadata;
var boundConstructor = modelMetadata.BoundConstructor;
if (boundConstructor != null)
{
// Only record types are allowed to have a BoundConstructor. Binding a record type requires
// instantiating the type. This means we'll ignore a previously assigned bindingContext.Model value.
// This behaior is identical to input formatting with S.T.Json and Json.NET.
var values = new object[boundConstructor.BoundConstructorParameters!.Count];
var (attemptedParameterBinding, parameterBindingSucceeded) = await BindParametersAsync(
bindingContext,
propertyData,
boundConstructor.BoundConstructorParameters,
values);
attemptedBinding |= attemptedParameterBinding;
bindingSucceeded |= parameterBindingSucceeded;
if (!CreateModel(bindingContext, boundConstructor, values))
{
return;
}
}
else if (bindingContext.Model == null)
{
CreateModel(bindingContext);
}
var (attemptedPropertyBinding, propertyBindingSucceeded) = await BindPropertiesAsync(
bindingContext,
propertyData,
modelMetadata.BoundProperties);
attemptedBinding |= attemptedPropertyBinding;
bindingSucceeded |= propertyBindingSucceeded;
// Have we created a top-level model despite an inability to bind anything in said model and a lack of
// other IsBindingRequired errors? Does that violate [BindRequired] on the model? This case occurs when
// 1. The top-level model has no public settable properties.
// 2. All properties in a [BindRequired] model have [BindNever] or are otherwise excluded from binding.
// 3. No data exists for any property.
if (!attemptedBinding &&
bindingContext.IsTopLevelObject &&
modelMetadata.IsBindingRequired)
{
var messageProvider = modelMetadata.ModelBindingMessageProvider;
var message = messageProvider.MissingBindRequiredValueAccessor(bindingContext.FieldName);
bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, message);
}
_logger.DoneAttemptingToBindModel(bindingContext);
// Have all binders failed because no data was available?
//
// If CanCreateModel determined a property has data, failures are likely due to conversion errors. For
// example, user may submit ?[0].id=twenty&[1].id=twenty-one&[2].id=22 for a collection of a complex type
// with an int id property. In that case, the bound model should be [ {}, {}, { id = 22 }] and
// ModelState should contain errors about both [0].id and [1].id. Do not inform higher-level binders of the
// failure in this and similar cases.
//
// If CanCreateModel could not find data for non-greedy properties, failures indicate greedy binders were
// unsuccessful. For example, user may submit file attachments [0].File and [1].File but not [2].File for
// a collection of a complex type containing an IFormFile property. In that case, we have exhausted the
// attached files and checking for [3].File is likely be pointless. (And, if it had a point, would we stop
// after 10 failures, 100, or more -- all adding redundant errors to ModelState?) Inform higher-level
// binders of the failure.
//
// Required properties do not change the logic below. Missed required properties cause ModelState errors
// but do not necessarily prevent further attempts to bind.
//
// This logic is intended to maximize correctness but does not avoid infinite loops or recursion when a
// greedy model binder succeeds unconditionally.
if (!bindingContext.IsTopLevelObject &&
!bindingSucceeded &&
propertyData == GreedyPropertiesMayHaveData)
{
bindingContext.Result = ModelBindingResult.Failed();
return;
}
bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
}
internal static bool CreateModel(ModelBindingContext bindingContext, ModelMetadata boundConstructor, object[] values)
{
try
{
bindingContext.Model = boundConstructor.BoundConstructorInvoker!(values);
return true;
}
catch (Exception ex)
{
AddModelError(ex, bindingContext.ModelName, bindingContext);
bindingContext.Result = ModelBindingResult.Failed();
return false;
}
}
/// <summary>
/// Creates suitable <see cref="object"/> for given <paramref name="bindingContext"/>.
/// </summary>
/// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
/// <returns>An <see cref="object"/> compatible with <see cref="ModelBindingContext.ModelType"/>.</returns>
internal void CreateModel(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// If model creator throws an exception, we want to propagate it back up the call stack, since the
// application developer should know that this was an invalid type to try to bind to.
if (_modelCreator == null)
{
// The following check causes the ComplexTypeModelBinder to NOT participate in binding structs as
// reflection does not provide information about the implicit parameterless constructor for a struct.
// This binder would eventually fail to construct an instance of the struct as the Linq's NewExpression
// compile fails to construct it.
var modelType = bindingContext.ModelType;
if (modelType.IsAbstract || modelType.GetConstructor(Type.EmptyTypes) == null)
{
var metadata = bindingContext.ModelMetadata;
switch (metadata.MetadataKind)
{
case ModelMetadataKind.Parameter:
throw new InvalidOperationException(
Resources.FormatComplexObjectModelBinder_NoSuitableConstructor_ForParameter(
modelType.FullName,
metadata.ParameterName));
case ModelMetadataKind.Property:
throw new InvalidOperationException(
Resources.FormatComplexObjectModelBinder_NoSuitableConstructor_ForProperty(
modelType.FullName,
metadata.PropertyName,
bindingContext.ModelMetadata.ContainerType!.FullName));
case ModelMetadataKind.Type:
throw new InvalidOperationException(
Resources.FormatComplexObjectModelBinder_NoSuitableConstructor_ForType(
modelType.FullName));
}
}
_modelCreator = Expression
.Lambda<Func<object>>(Expression.New(bindingContext.ModelType))
.Compile();
}
bindingContext.Model = _modelCreator();
}
private async ValueTask<(bool attemptedBinding, bool bindingSucceeded)> BindParametersAsync(
ModelBindingContext bindingContext,
int propertyData,
IReadOnlyList<ModelMetadata> parameters,
object?[] parameterValues)
{
var attemptedBinding = false;
var bindingSucceeded = false;
if (parameters.Count == 0)
{
return (attemptedBinding, bindingSucceeded);
}
var postponePlaceholderBinding = false;
for (var i = 0; i < parameters.Count; i++)
{
var parameter = parameters[i];
var fieldName = parameter.BinderModelName ?? parameter.ParameterName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
if (!CanBindItem(bindingContext, parameter))
{
continue;
}
var parameterBinder = _parameterBinders[i];
if (parameterBinder is PlaceholderBinder)
{
if (postponePlaceholderBinding)
{
// Decided to postpone binding properties that complete a loop in the model types when handling
// an earlier loop-completing property. Postpone binding this property too.
continue;
}
else if (!bindingContext.IsTopLevelObject &&
!bindingSucceeded &&
propertyData == GreedyPropertiesMayHaveData)
{
// Have no confirmation of data for the current instance. Postpone completing the loop until
// we _know_ the current instance is useful. Recursion would otherwise occur prior to the
// block with a similar condition after the loop.
//
// Example cases include an Employee class containing
// 1. a Manager property of type Employee
// 2. an Employees property of type IList<Employee>
postponePlaceholderBinding = true;
continue;
}
}
var result = await BindParameterAsync(bindingContext, parameter, parameterBinder, fieldName, modelName);
if (result.IsModelSet)
{
attemptedBinding = true;
bindingSucceeded = true;
parameterValues[i] = result.Model;
}
else if (parameter.IsBindingRequired)
{
attemptedBinding = true;
}
}
if (postponePlaceholderBinding && bindingSucceeded)
{
// Have some data for this instance. Continue with the model type loop.
for (var i = 0; i < parameters.Count; i++)
{
var parameter = parameters[i];
if (!CanBindItem(bindingContext, parameter))
{
continue;
}
var parameterBinder = _parameterBinders[i];
if (parameterBinder is PlaceholderBinder)
{
var fieldName = parameter.BinderModelName ?? parameter.ParameterName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
var result = await BindParameterAsync(bindingContext, parameter, parameterBinder, fieldName, modelName);
if (result.IsModelSet)
{
parameterValues[i] = result.Model;
}
}
}
}
return (attemptedBinding, bindingSucceeded);
}
private async ValueTask<(bool attemptedBinding, bool bindingSucceeded)> BindPropertiesAsync(
ModelBindingContext bindingContext,
int propertyData,
IReadOnlyList<ModelMetadata> boundProperties)
{
var attemptedBinding = false;
var bindingSucceeded = false;
if (boundProperties.Count == 0)
{
return (attemptedBinding, bindingSucceeded);
}
var postponePlaceholderBinding = false;
for (var i = 0; i < boundProperties.Count; i++)
{
var property = boundProperties[i];
if (!CanBindItem(bindingContext, property))
{
continue;
}
var propertyBinder = _propertyBinders[property];
if (propertyBinder is PlaceholderBinder)
{
if (postponePlaceholderBinding)
{
// Decided to postpone binding properties that complete a loop in the model types when handling
// an earlier loop-completing property. Postpone binding this property too.
continue;
}
else if (!bindingContext.IsTopLevelObject &&
!bindingSucceeded &&
propertyData == GreedyPropertiesMayHaveData)
{
// Have no confirmation of data for the current instance. Postpone completing the loop until
// we _know_ the current instance is useful. Recursion would otherwise occur prior to the
// block with a similar condition after the loop.
//
// Example cases include an Employee class containing
// 1. a Manager property of type Employee
// 2. an Employees property of type IList<Employee>
postponePlaceholderBinding = true;
continue;
}
}
var fieldName = property.BinderModelName ?? property.PropertyName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
var result = await BindPropertyAsync(bindingContext, property, propertyBinder, fieldName, modelName);
if (result.IsModelSet)
{
attemptedBinding = true;
bindingSucceeded = true;
}
else if (property.IsBindingRequired)
{
attemptedBinding = true;
}
}
if (postponePlaceholderBinding && bindingSucceeded)
{
// Have some data for this instance. Continue with the model type loop.
for (var i = 0; i < boundProperties.Count; i++)
{
var property = boundProperties[i];
if (!CanBindItem(bindingContext, property))
{
continue;
}
var propertyBinder = _propertyBinders[property];
if (propertyBinder is PlaceholderBinder)
{
var fieldName = property.BinderModelName ?? property.PropertyName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
await BindPropertyAsync(bindingContext, property, propertyBinder, fieldName, modelName);
}
}
}
return (attemptedBinding, bindingSucceeded);
}
internal bool CanBindItem(ModelBindingContext bindingContext, ModelMetadata propertyMetadata)
{
var metadataProviderFilter = bindingContext.ModelMetadata.PropertyFilterProvider?.PropertyFilter;
if (metadataProviderFilter?.Invoke(propertyMetadata) == false)
{
return false;
}
if (bindingContext.PropertyFilter?.Invoke(propertyMetadata) == false)
{
return false;
}
if (!propertyMetadata.IsBindingAllowed)
{
return false;
}
if (propertyMetadata.MetadataKind == ModelMetadataKind.Property && propertyMetadata.IsReadOnly)
{
// Determine if we can update a readonly property (such as a collection).
return CanUpdateReadOnlyProperty(propertyMetadata.ModelType);
}
return true;
}
private async ValueTask<ModelBindingResult> BindPropertyAsync(
ModelBindingContext bindingContext,
ModelMetadata property,
IModelBinder propertyBinder,
string fieldName,
string modelName)
{
Debug.Assert(property.MetadataKind == ModelMetadataKind.Property);
// Pass complex (including collection) values down so that binding system does not unnecessarily
// recreate instances or overwrite inner properties that are not bound. No need for this with simple
// values because they will be overwritten if binding succeeds. Arrays are never reused because they
// cannot be resized.
object? propertyModel = null;
if (property.PropertyGetter != null &&
property.IsComplexType &&
!property.ModelType.IsArray)
{
propertyModel = property.PropertyGetter(bindingContext.Model!);
}
ModelBindingResult result;
using (bindingContext.EnterNestedScope(
modelMetadata: property,
fieldName: fieldName,
modelName: modelName,
model: propertyModel))
{
await propertyBinder.BindModelAsync(bindingContext);
result = bindingContext.Result;
}
if (result.IsModelSet)
{
SetProperty(bindingContext, modelName, property, result);
}
else if (property.IsBindingRequired)
{
var message = property.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
bindingContext.ModelState.TryAddModelError(modelName, message);
}
return result;
}
private async ValueTask<ModelBindingResult> BindParameterAsync(
ModelBindingContext bindingContext,
ModelMetadata parameter,
IModelBinder parameterBinder,
string fieldName,
string modelName)
{
Debug.Assert(parameter.MetadataKind == ModelMetadataKind.Parameter);
ModelBindingResult result;
using (bindingContext.EnterNestedScope(
modelMetadata: parameter,
fieldName: fieldName,
modelName: modelName,
model: null))
{
await parameterBinder.BindModelAsync(bindingContext);
result = bindingContext.Result;
}
if (!result.IsModelSet && parameter.IsBindingRequired)
{
var message = parameter.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
bindingContext.ModelState.TryAddModelError(modelName, message);
}
return result;
}
internal int CanCreateModel(ModelBindingContext bindingContext)
{
var isTopLevelObject = bindingContext.IsTopLevelObject;
// If we get here the model is a complex object which was not directly bound by any previous model binder,
// so we want to decide if we want to continue binding. This is important to get right to avoid infinite
// recursion.
//
// First, we want to make sure this object is allowed to come from a value provider source as this binder
// will only include value provider data. For instance if the model is marked with [FromBody], then we
// can just skip it. A greedy source cannot be a value provider.
//
// If the model isn't marked with ANY binding source, then we assume it's OK also.
//
// We skip this check if it is a top level object because we want to always evaluate
// the creation of top level object (this is also required for ModelBinderAttribute to work.)
var bindingSource = bindingContext.BindingSource;
if (!isTopLevelObject && bindingSource != null && bindingSource.IsGreedy)
{
return NoDataAvailable;
}
// Create the object if:
// 1. It is a top level model.
if (isTopLevelObject)
{
return ValueProviderDataAvailable;
}
// 2. Any of the model properties can be bound.
return CanBindAnyModelItem(bindingContext);
}
private int CanBindAnyModelItem(ModelBindingContext bindingContext)
{
// If there are no properties on the model, and no constructor parameters, there is nothing to bind. We are here means this is not a top
// level object. So we return false.
var modelMetadata = bindingContext.ModelMetadata;
var performsConstructorBinding = bindingContext.Model == null && modelMetadata.BoundConstructor != null;
if (modelMetadata.Properties.Count == 0 &&
(!performsConstructorBinding || modelMetadata.BoundConstructor!.BoundConstructorParameters!.Count == 0))
{
Log.NoPublicSettableItems(_logger, bindingContext);
return NoDataAvailable;
}
// We want to check to see if any of the properties of the model can be bound using the value providers or
// a greedy binder.
//
// Because a property might specify a custom binding source ([FromForm]), it's not correct
// for us to just try bindingContext.ValueProvider.ContainsPrefixAsync(bindingContext.ModelName);
// that may include other value providers - that would lead us to mistakenly create the model
// when the data is coming from a source we should use (ex: value found in query string, but the
// model has [FromForm]).
//
// To do this we need to enumerate the properties, and see which of them provide a binding source
// through metadata, then we decide what to do.
//
// If a property has a binding source, and it's a greedy source, then it's always bound.
//
// If a property has a binding source, and it's a non-greedy source, then we'll filter the
// the value providers to just that source, and see if we can find a matching prefix
// (see CanBindValue).
//
// If a property does not have a binding source, then it's fair game for any value provider.
//
// Bottom line, if any property meets the above conditions and has a value from ValueProviders, then we'll
// create the model and try to bind it. Of, if ANY properties of the model have a greedy source,
// then we go ahead and create it.
var hasGreedyBinders = false;
for (var i = 0; i < bindingContext.ModelMetadata.Properties.Count; i++)
{
var propertyMetadata = bindingContext.ModelMetadata.Properties[i];
if (!CanBindItem(bindingContext, propertyMetadata))
{
continue;
}
// If any property can be bound from a greedy binding source, then success.
var bindingSource = propertyMetadata.BindingSource;
if (bindingSource != null && bindingSource.IsGreedy)
{
hasGreedyBinders = true;
continue;
}
// Otherwise, check whether the (perhaps filtered) value providers have a match.
var fieldName = propertyMetadata.BinderModelName ?? propertyMetadata.PropertyName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
using (bindingContext.EnterNestedScope(
modelMetadata: propertyMetadata,
fieldName: fieldName,
modelName: modelName,
model: null))
{
// If any property can be bound from a value provider, then success.
if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
return ValueProviderDataAvailable;
}
}
}
if (performsConstructorBinding)
{
var parameters = bindingContext.ModelMetadata.BoundConstructor!.BoundConstructorParameters!;
for (var i = 0; i < parameters.Count; i++)
{
var parameterMetadata = parameters[i];
if (!CanBindItem(bindingContext, parameterMetadata))
{
continue;
}
// If any parameter can be bound from a greedy binding source, then success.
var bindingSource = parameterMetadata.BindingSource;
if (bindingSource != null && bindingSource.IsGreedy)
{
hasGreedyBinders = true;
continue;
}
// Otherwise, check whether the (perhaps filtered) value providers have a match.
var fieldName = parameterMetadata.BinderModelName ?? parameterMetadata.ParameterName!;
var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
using (bindingContext.EnterNestedScope(
modelMetadata: parameterMetadata,
fieldName: fieldName,
modelName: modelName,
model: null))
{
// If any parameter can be bound from a value provider, then success.
if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
{
return ValueProviderDataAvailable;
}
}
}
}
if (hasGreedyBinders)
{
return GreedyPropertiesMayHaveData;
}
_logger.CannotBindToComplexType(bindingContext);
return NoDataAvailable;
}
internal static bool CanUpdateReadOnlyProperty(Type propertyType)
{
// Value types have copy-by-value semantics, which prevents us from updating
// properties that are marked readonly.
if (propertyType.IsValueType)
{
return false;
}
// Arrays are strange beasts since their contents are mutable but their sizes aren't.
// Therefore we shouldn't even try to update these. Further reading:
// http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx
if (propertyType.IsArray)
{
return false;
}
// Special-case known immutable reference types
if (propertyType == typeof(string))
{
return false;
}
return true;
}
internal void SetProperty(
ModelBindingContext bindingContext,
string modelName,
ModelMetadata propertyMetadata,
ModelBindingResult result)
{
if (!result.IsModelSet)
{
// If we don't have a value, don't set it on the model and trounce a pre-initialized value.
return;
}
if (propertyMetadata.IsReadOnly)
{
// The property should have already been set when we called BindPropertyAsync, so there's
// nothing to do here.
return;
}
var value = result.Model;
try
{
propertyMetadata.PropertySetter!(bindingContext.Model!, value);
}
catch (Exception exception)
{
AddModelError(exception, modelName, bindingContext);
}
}
private static void AddModelError(
Exception exception,
string modelName,
ModelBindingContext bindingContext)
{
var targetInvocationException = exception as TargetInvocationException;
if (targetInvocationException?.InnerException != null)
{
exception = targetInvocationException.InnerException;
}
// Do not add an error message if a binding error has already occurred for this property.
var modelState = bindingContext.ModelState;
var validationState = modelState.GetFieldValidationState(modelName);
if (validationState == ModelValidationState.Unvalidated)
{
modelState.AddModelError(modelName, exception, bindingContext.ModelMetadata);
}
}
private static partial class Log
{
[LoggerMessage(17, LogLevel.Debug, "Could not bind to model with name '{ModelName}' and type '{ModelType}' as the type has no " +
"public settable properties or constructor parameters.", EventName = "NoPublicSettableItems")]
public static partial void NoPublicSettableItems(ILogger logger, string modelName, Type modelType);
public static void NoPublicSettableItems(ILogger logger, ModelBindingContext bindingContext)
{
NoPublicSettableItems(logger, bindingContext.ModelName, bindingContext.ModelType);
}
}
}
}
| |
// 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.ObjectModel;
using System.IdentityModel.Claims;
using System.IdentityModel.Policy;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime;
using System.ServiceModel.Diagnostics;
using System.Runtime.Diagnostics;
namespace System.ServiceModel.Security
{
public abstract class IdentityVerifier
{
protected IdentityVerifier()
{
// empty
}
public static IdentityVerifier CreateDefault()
{
return DefaultIdentityVerifier.Instance;
}
public abstract bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext);
public abstract bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity);
private static void AdjustAddress(ref EndpointAddress reference, Uri via)
{
// if we don't have an identity and we have differing Uris, we should use the Via
if (reference.Identity == null && reference.Uri != via)
{
reference = new EndpointAddress(via);
}
}
internal bool TryGetIdentity(EndpointAddress reference, Uri via, out EndpointIdentity identity)
{
AdjustAddress(ref reference, via);
return TryGetIdentity(reference, out identity);
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, Uri via, AuthorizationContext authorizationContext)
{
AdjustAddress(ref serviceReference, via);
EnsureIdentity(serviceReference, authorizationContext, SR.IdentityCheckFailedForOutgoingMessage);
}
internal void EnsureOutgoingIdentity(EndpointAddress serviceReference, ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies)
{
if (authorizationPolicies == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authorizationPolicies));
}
AuthorizationContext ac = AuthorizationContext.CreateDefaultAuthorizationContext(authorizationPolicies);
EnsureIdentity(serviceReference, ac, SR.IdentityCheckFailedForOutgoingMessage);
}
private void EnsureIdentity(EndpointAddress serviceReference, AuthorizationContext authorizationContext, String errorString)
{
if (authorizationContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authorizationContext));
}
EndpointIdentity identity;
if (!TryGetIdentity(serviceReference, out identity))
{
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authorizationContext, GetType());
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new MessageSecurityException(SR.Format(errorString, identity, serviceReference)));
}
else
{
if (!CheckAccess(identity, authorizationContext))
{
// CheckAccess performs a Trace on failure, no need to do it twice
Exception e = CreateIdentityCheckException(identity, authorizationContext, errorString, serviceReference);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(e);
}
}
}
private Exception CreateIdentityCheckException(EndpointIdentity identity, AuthorizationContext authorizationContext, string errorString, EndpointAddress serviceReference)
{
Exception result;
if (identity.IdentityClaim != null
&& identity.IdentityClaim.ClaimType == ClaimTypes.Dns
&& identity.IdentityClaim.Right == Rights.PossessProperty
&& identity.IdentityClaim.Resource is string)
{
string expectedDnsName = (string)identity.IdentityClaim.Resource;
string actualDnsName = null;
for (int i = 0; i < authorizationContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authorizationContext.ClaimSets[i];
foreach (Claim claim in claimSet.FindClaims(ClaimTypes.Dns, Rights.PossessProperty))
{
if (claim.Resource is string)
{
actualDnsName = (string)claim.Resource;
break;
}
}
if (actualDnsName != null)
{
break;
}
}
if (SR.IdentityCheckFailedForIncomingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForIncomingMessage, expectedDnsName, actualDnsName));
}
}
else if (SR.IdentityCheckFailedForOutgoingMessage.Equals(errorString))
{
if (actualDnsName == null)
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessageLackOfDnsClaim, expectedDnsName));
}
else
{
result = new MessageSecurityException(SR.Format(SR.DnsIdentityCheckFailedForOutgoingMessage, expectedDnsName, actualDnsName));
}
}
else
{
result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
}
}
else
{
result = new MessageSecurityException(SR.Format(errorString, identity, serviceReference));
}
return result;
}
private class DefaultIdentityVerifier : IdentityVerifier
{
public static DefaultIdentityVerifier Instance { get; } = new DefaultIdentityVerifier();
public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
{
if (reference == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reference));
}
identity = reference.Identity;
if (identity == null)
{
identity = TryCreateDnsIdentity(reference);
}
if (identity == null)
{
SecurityTraceRecordHelper.TraceIdentityDeterminationFailure(reference, typeof(DefaultIdentityVerifier));
return false;
}
else
{
SecurityTraceRecordHelper.TraceIdentityDeterminationSuccess(reference, identity, typeof(DefaultIdentityVerifier));
return true;
}
}
private EndpointIdentity TryCreateDnsIdentity(EndpointAddress reference)
{
Uri toAddress = reference.Uri;
if (!toAddress.IsAbsoluteUri)
{
return null;
}
return EndpointIdentity.CreateDnsIdentity(toAddress.DnsSafeHost);
}
internal Claim CheckDnsEquivalence(ClaimSet claimSet, string expectedSpn)
{
// host/<machine-name> satisfies the DNS identity claim
IEnumerable<Claim> claims = claimSet.FindClaims(ClaimTypes.Spn, Rights.PossessProperty);
foreach (Claim claim in claims)
{
if (expectedSpn.Equals((string)claim.Resource, StringComparison.OrdinalIgnoreCase))
{
return claim;
}
}
return null;
}
public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
{
EventTraceActivity eventTraceActivity = null;
if (identity == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(identity));
}
if (authContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(authContext));
}
if (FxTrace.Trace.IsEnd2EndActivityTracingEnabled)
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity((OperationContext.Current != null) ? OperationContext.Current.IncomingMessage : null);
}
for (int i = 0; i < authContext.ClaimSets.Count; ++i)
{
ClaimSet claimSet = authContext.ClaimSets[i];
if (claimSet.ContainsClaim(identity.IdentityClaim))
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, identity.IdentityClaim, GetType());
return true;
}
// try Claim equivalence
string expectedSpn = null;
if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
{
expectedSpn = string.Format(CultureInfo.InvariantCulture, "host/{0}", (string)identity.IdentityClaim.Resource);
Claim claim = CheckDnsEquivalence(claimSet, expectedSpn);
if (claim != null)
{
SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, GetType());
return true;
}
}
// Allow a Sid claim to support UPN, and SPN identities
// SID claims not available yet
//SecurityIdentifier identitySid = null;
//if (ClaimTypes.Sid.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Sid");
//}
//else if (ClaimTypes.Upn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Upn");
//}
//else if (ClaimTypes.Spn.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Spn");
//}
//else if (ClaimTypes.Dns.Equals(identity.IdentityClaim.ClaimType))
//{
// throw ExceptionHelper.PlatformNotSupported("DefaultIdentityVerifier - ClaimTypes.Dns");
//}
//if (identitySid != null)
//{
// Claim claim = CheckSidEquivalence(identitySid, claimSet);
// if (claim != null)
// {
// SecurityTraceRecordHelper.TraceIdentityVerificationSuccess(eventTraceActivity, identity, claim, this.GetType());
// return true;
// }
//}
}
SecurityTraceRecordHelper.TraceIdentityVerificationFailure(identity, authContext, GetType());
if (WcfEventSource.Instance.SecurityIdentityVerificationFailureIsEnabled())
{
WcfEventSource.Instance.SecurityIdentityVerificationFailure(eventTraceActivity);
}
return false;
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2009-2015 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.TestCaseSourceAttributeFixture;
using NUnit.TestUtilities;
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class TestCaseSourceTests : TestSourceMayBeInherited
{
#region Tests With Static and Instance Members as Source
[Test, TestCaseSource(nameof(StaticProperty))]
public void SourceCanBeStaticProperty(string source)
{
Assert.AreEqual("StaticProperty", source);
}
[Test, TestCaseSource(nameof(InheritedStaticProperty))]
public void TestSourceCanBeInheritedStaticProperty(bool source)
{
Assert.AreEqual(true, source);
}
static IEnumerable StaticProperty
{
get { return new object[] { new object[] { "StaticProperty" } }; }
}
[Test]
public void SourceUsingInstancePropertyIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithInstancePropertyAsSource));
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
[Test, TestCaseSource(nameof(StaticMethod))]
public void SourceCanBeStaticMethod(string source)
{
Assert.AreEqual("StaticMethod", source);
}
static IEnumerable StaticMethod()
{
return new object[] { new object[] { "StaticMethod" } };
}
[Test]
public void SourceUsingInstanceMethodIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithInstanceMethodAsSource));
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
IEnumerable InstanceMethod()
{
return new object[] { new object[] { "InstanceMethod" } };
}
[Test, TestCaseSource(nameof(StaticField))]
public void SourceCanBeStaticField(string source)
{
Assert.AreEqual("StaticField", source);
}
static object[] StaticField =
{ new object[] { "StaticField" } };
[Test]
public void SourceUsingInstanceFieldIsNotRunnable()
{
var result = TestBuilder.RunParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithInstanceFieldAsSource));
Assert.AreEqual(result.Children.ToArray()[0].ResultState, ResultState.NotRunnable);
}
#endregion
#region Test With IEnumerable Class as Source
[Test, TestCaseSource(typeof(DataSourceClass))]
public void SourceCanBeInstanceOfIEnumerable(string source)
{
Assert.AreEqual("DataSourceClass", source);
}
class DataSourceClass : IEnumerable
{
public DataSourceClass()
{
}
public IEnumerator GetEnumerator()
{
yield return "DataSourceClass";
}
}
#endregion
[Test, TestCaseSource(nameof(MyData))]
public void SourceMayReturnArgumentsAsObjectArray(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCaseSource(nameof(MyData))]
public void TestAttributeIsOptional(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource(nameof(MyIntData))]
public void SourceMayReturnArgumentsAsIntArray(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource(nameof(MyArrayData))]
public void SourceMayReturnArrayForArray(int[] array)
{
Assert.That(true);
}
[Test, TestCaseSource(nameof(EvenNumbers))]
public void SourceMayReturnSinglePrimitiveArgumentAlone(int n)
{
Assert.AreEqual(0, n % 2);
}
[Test, TestCaseSource(nameof(Params))]
public int SourceMayReturnArgumentsAsParamSet(int n, int d)
{
return n / d;
}
[Test]
[TestCaseSource(nameof(MyData))]
[TestCaseSource(nameof(MoreData), Category = "Extra")]
[TestCase(12, 2, 6)]
public void TestMayUseMultipleSourceAttributes(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, TestCaseSource(nameof(FourArgs))]
public void TestWithFourArguments(int n, int d, int q, int r)
{
Assert.AreEqual(q, n / d);
Assert.AreEqual(r, n % d);
}
[Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), nameof(DivideDataProvider.HereIsTheData))]
public void SourceMayBeInAnotherClass(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, Category("Top"), TestCaseSource(typeof(DivideDataProvider), "HereIsTheDataWithParameters", new object[] { 100, 4, 25 })]
public void SourceInAnotherClassPassingSomeDataToConstructor(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test, Category("Top"), TestCaseSource(nameof(StaticMethodDataWithParameters), new object[] { 8000, 8, 1000 })]
public void SourceCanBeStaticMethodPassingSomeDataToConstructor(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[Test]
public void SourceInAnotherClassPassingParamsToField()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.SourceInAnotherClassPassingParamsToField)).Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have specified a data source field but also given a set of parameters. Fields cannot take parameters, " +
"please revise the 3rd parameter passed to the TestCaseSourceAttribute and either remove " +
"it or specify a method.", result.Message);
}
[Test]
public void SourceInAnotherClassPassingParamsToProperty()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.SourceInAnotherClassPassingParamsToProperty)).Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have specified a data source property but also given a set of parameters. " +
"Properties cannot take parameters, please revise the 3rd parameter passed to the " +
"TestCaseSource attribute and either remove it or specify a method.", result.Message);
}
[Test]
public void SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.SourceInAnotherClassPassingSomeDataToConstructorWrongNumberParam)).Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("You have given the wrong number of arguments to the method in the TestCaseSourceAttribute" +
", please check the number of parameters passed in the object is correct in the 3rd parameter for the " +
"TestCaseSourceAttribute and this matches the number of parameters in the target method and try again.", result.Message);
}
[Test, TestCaseSource(typeof(DivideDataProviderWithReturnValue), nameof(DivideDataProviderWithReturnValue.TestCases))]
public int SourceMayBeInAnotherClassWithReturn(int n, int d)
{
return n / d;
}
[Test]
public void IgnoreTakesPrecedenceOverExpectedException()
{
var result = TestBuilder.RunParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodCallsIgnore)).Children.ToArray()[0];
Assert.AreEqual(ResultState.Ignored, result.ResultState);
Assert.AreEqual("Ignore this", result.Message);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithIgnoredTestCases));
Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!"));
}
[Test]
public void CanMarkIndividualTestCasesExplicit()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithExplicitTestCases));
Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing"));
}
[Test]
public void HandlesExceptionInTestCaseSource()
{
var testMethod = (TestMethod)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithSourceThrowingException)).Tests[0];
Assert.AreEqual(RunState.NotRunnable, testMethod.RunState);
ITestResult result = TestBuilder.RunTest(testMethod, null);
Assert.AreEqual(ResultState.NotRunnable, result.ResultState);
Assert.AreEqual("System.Exception : my message", result.Message);
}
[TestCaseSource(nameof(exception_source)), Explicit("Used for GUI tests")]
public void HandlesExceptionInTestCaseSource_GuiDisplay(string lhs, string rhs)
{
Assert.AreEqual(lhs, rhs);
}
private static IEnumerable<TestCaseData> ZeroTestCasesSource() => Enumerable.Empty<TestCaseData>();
[TestCaseSource(nameof(ZeroTestCasesSource))]
public void TestWithZeroTestSourceCasesShouldPassWithoutRequiringArguments(int requiredParameter)
{
}
[Test]
public void TestMethodIsNotRunnableWhenSourceDoesNotExist()
{
TestSuite suiteToTest = TestBuilder.MakeParameterizedMethodSuite(typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithNonExistingSource));
Assert.That(suiteToTest.Tests.Count == 1);
Assert.AreEqual(RunState.NotRunnable, suiteToTest.Tests[0].RunState);
}
static object[] testCases =
{
new TestCaseData(
new string[] { "A" },
new string[] { "B" })
};
[Test, TestCaseSource(nameof(testCases))]
public void MethodTakingTwoStringArrays(string[] a, string[] b)
{
Assert.That(a, Is.TypeOf(typeof(string[])));
Assert.That(b, Is.TypeOf(typeof(string[])));
}
[TestCaseSource(nameof(SingleMemberArrayAsArgument))]
public void Issue1337SingleMemberArrayAsArgument(string[] args)
{
Assert.That(args.Length == 1 && args[0] == "1");
}
static string[][] SingleMemberArrayAsArgument = { new[] { "1" } };
#region Test name tests
public static IEnumerable<TestCaseData> IndividualInstanceNameTestDataSource()
{
var suite = (ParameterizedMethodSuite)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture),
nameof(TestCaseSourceAttributeFixture.TestCaseNameTestDataMethod));
foreach (var test in suite.Tests)
{
var expectedName = (string)test.Properties.Get("ExpectedTestName");
yield return new TestCaseData(test, expectedName)
.SetArgDisplayNames(expectedName); // SetArgDisplayNames (here) is purely cosmetic for the purposes of these tests
}
}
[TestCaseSource(nameof(IndividualInstanceNameTestDataSource))]
public static void IndividualInstanceName(ITest test, string expectedName)
{
Assert.That(test.Name, Is.EqualTo(expectedName));
}
[TestCaseSource(nameof(IndividualInstanceNameTestDataSource))]
public static void IndividualInstanceFullName(ITest test, string expectedName)
{
var expectedFullName = typeof(TestCaseSourceAttributeFixture).FullName + "." + expectedName;
Assert.That(test.FullName, Is.EqualTo(expectedFullName));
}
#endregion
[Test]
public void TestNameIntrospectsArrayValues()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseSourceAttributeFixture), nameof(TestCaseSourceAttributeFixture.MethodWithArrayArguments));
Assert.That(suite.TestCaseCount, Is.EqualTo(5));
Assert.Multiple(() =>
{
Assert.That(suite.Tests[0].Name, Is.EqualTo(@"MethodWithArrayArguments([1, ""text"", System.Object])"));
Assert.That(suite.Tests[1].Name, Is.EqualTo(@"MethodWithArrayArguments([])"));
Assert.That(suite.Tests[2].Name, Is.EqualTo(@"MethodWithArrayArguments([1, Int32[], 4])"));
Assert.That(suite.Tests[3].Name, Is.EqualTo(@"MethodWithArrayArguments([1, 2, 3, 4, 5, ...])"));
Assert.That(suite.Tests[4].Name, Is.EqualTo(@"MethodWithArrayArguments([System.Byte[,]])"));
});
}
#region Sources used by the tests
static object[] MyData = new object[] {
new object[] { 12, 3, 4 },
new object[] { 12, 4, 3 },
new object[] { 12, 6, 2 } };
static object[] MyIntData = new object[] {
new int[] { 12, 3, 4 },
new int[] { 12, 4, 3 },
new int[] { 12, 6, 2 } };
static object[] MyArrayData = new object[]
{
new int[] { 12 },
new int[] { 12, 4 },
new int[] { 12, 6, 2 }
};
public static IEnumerable StaticMethodDataWithParameters(int inject1, int inject2, int inject3)
{
yield return new object[] { inject1, inject2, inject3 };
}
static object[] FourArgs = new object[] {
new TestCaseData( 12, 3, 4, 0 ),
new TestCaseData( 12, 4, 3, 0 ),
new TestCaseData( 12, 5, 2, 2 ) };
static int[] EvenNumbers = new int[] { 2, 4, 6, 8 };
static object[] MoreData = new object[] {
new object[] { 12, 1, 12 },
new object[] { 12, 2, 6 } };
static object[] Params = new object[] {
new TestCaseData(24, 3).Returns(8),
new TestCaseData(24, 2).Returns(12) };
private class DivideDataProvider
{
#pragma warning disable 0169 // x is never assigned
private static object[] myObject;
#pragma warning restore 0169
public static IEnumerable HereIsTheDataWithParameters(int inject1, int inject2, int inject3)
{
yield return new object[] { inject1, inject2, inject3 };
}
public static IEnumerable HereIsTheData
{
get
{
yield return new object[] { 100, 20, 5 };
yield return new object[] { 100, 4, 25 };
}
}
}
public class DivideDataProviderWithReturnValue
{
public static IEnumerable TestCases
{
get
{
return new object[] {
new TestCaseData(12, 3).Returns(4).SetName("TC1"),
new TestCaseData(12, 2).Returns(6).SetName("TC2"),
new TestCaseData(12, 4).Returns(3).SetName("TC3")
};
}
}
}
private static IEnumerable exception_source
{
get
{
yield return new TestCaseData("a", "a");
yield return new TestCaseData("b", "b");
throw new System.Exception("my message");
}
}
#endregion
}
public class TestSourceMayBeInherited
{
protected static IEnumerable<bool> InheritedStaticProperty
{
get { yield return true; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using SimBitConsulting.Areas.HelpPage.ModelDescriptions;
using SimBitConsulting.Areas.HelpPage.Models;
namespace SimBitConsulting.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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;
using System.Configuration;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Win32;
using SysTx = System.Transactions;
namespace System.Data.Common
{
internal static class ADP
{
internal static Exception ExceptionWithStackTrace(Exception e)
{
try
{
throw e;
}
catch (Exception caught)
{
return caught;
}
}
private static void TraceException(string trace, Exception e)
{
Debug.Assert(e != null, "TraceException: null Exception");
if (e != null)
{
DataCommonEventSource.Log.Trace(trace, e);
}
}
internal static void TraceExceptionAsReturnValue(Exception e)
{
TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
}
internal static void TraceExceptionForCapture(Exception e)
{
Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
}
internal static void TraceExceptionWithoutRethrow(Exception e)
{
Debug.Assert(ADP.IsCatchableExceptionType(e), "Invalid exception type, should have been re-thrown!");
TraceException("<comm.ADP.TraceException|ERR|CATCH> '%ls'\n", e);
}
//
// COM+ exceptions
//
internal static ArgumentException Argument(string error)
{
ArgumentException e = new ArgumentException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, Exception inner)
{
ArgumentException e = new ArgumentException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, string parameter)
{
ArgumentException e = new ArgumentException(error, parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException Argument(string error, string parameter, Exception inner)
{
ArgumentException e = new ArgumentException(error, parameter, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter)
{
ArgumentNullException e = new ArgumentNullException(parameter);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentNullException ArgumentNull(string parameter, string error)
{
ArgumentNullException e = new ArgumentNullException(parameter, error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
{
ArgumentOutOfRangeException e = new ArgumentOutOfRangeException(parameterName, message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static ConfigurationException Configuration(string message)
{
ConfigurationException e = new ConfigurationErrorsException(message);
TraceExceptionAsReturnValue(e);
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange(string error)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidCastException InvalidCast(string error)
{
return InvalidCast(error, null);
}
internal static InvalidCastException InvalidCast(string error, Exception inner)
{
InvalidCastException e = new InvalidCastException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException InvalidOperation(string error)
{
InvalidOperationException e = new InvalidOperationException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static TimeoutException TimeoutException(string error)
{
TimeoutException e = new TimeoutException(error);
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException InvalidOperation(string error, Exception inner)
{
InvalidOperationException e = new InvalidOperationException(error, inner);
TraceExceptionAsReturnValue(e);
return e;
}
internal static NotSupportedException NotSupported()
{
NotSupportedException e = new NotSupportedException();
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidCastException InvalidCast()
{
InvalidCastException e = new InvalidCastException();
TraceExceptionAsReturnValue(e);
return e;
}
internal static InvalidOperationException DataAdapter(string error)
{
return InvalidOperation(error);
}
internal static InvalidOperationException DataAdapter(string error, Exception inner)
{
return InvalidOperation(error, inner);
}
private static InvalidOperationException Provider(string error)
{
return InvalidOperation(error);
}
internal static ArgumentException InvalidMultipartName(string property, string value)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartName, SR.GetString(property), value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameIncorrectUsageOfQuotes(string property, string value)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartNameQuoteUsage, SR.GetString(property), value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidMultipartNameToManyParts(string property, string value, int limit)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidMultipartNameToManyParts, SR.GetString(property), value, limit));
TraceExceptionAsReturnValue(e);
return e;
}
//
// Helper Functions
//
internal static void CheckArgumentLength(string value, string parameterName)
{
CheckArgumentNull(value, parameterName);
if (0 == value.Length)
{
throw Argument(SR.GetString(SR.ADP_EmptyString, parameterName));
}
}
internal static void CheckArgumentNull(object value, string parameterName)
{
if (null == value)
{
throw ArgumentNull(parameterName);
}
}
// only StackOverflowException & ThreadAbortException are sealed classes
private static readonly Type StackOverflowType = typeof(StackOverflowException);
private static readonly Type OutOfMemoryType = typeof(OutOfMemoryException);
private static readonly Type ThreadAbortType = typeof(ThreadAbortException);
private static readonly Type NullReferenceType = typeof(NullReferenceException);
private static readonly Type AccessViolationType = typeof(AccessViolationException);
private static readonly Type SecurityType = typeof(SecurityException);
internal static bool IsCatchableExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != StackOverflowType) &&
(type != OutOfMemoryType) &&
(type != ThreadAbortType) &&
(type != NullReferenceType) &&
(type != AccessViolationType) &&
!SecurityType.IsAssignableFrom(type));
}
internal static bool IsCatchableOrSecurityExceptionType(Exception e)
{
// a 'catchable' exception is defined by what it is not.
// since IsCatchableExceptionType defined SecurityException as not 'catchable'
// this method will return true for SecurityException has being catchable.
// the other way to write this method is, but then SecurityException is checked twice
// return ((e is SecurityException) || IsCatchableExceptionType(e));
Debug.Assert(e != null, "Unexpected null exception!");
Type type = e.GetType();
return ((type != StackOverflowType) &&
(type != OutOfMemoryType) &&
(type != ThreadAbortType) &&
(type != NullReferenceType) &&
(type != AccessViolationType));
}
// Invalid Enumeration
internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
{
return ADP.ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name);
}
// IDbCommand.CommandType
internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Assert(false, "valid CommandType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
}
// IDataParameter.SourceVersion
internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
switch (value)
{
case DataRowVersion.Default:
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
Debug.Assert(false, "valid DataRowVersion " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
}
// IDbConnection.BeginTransaction, OleDbTransaction.Begin
internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Assert(false, "valid IsolationLevel " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
}
// IDataParameter.Direction
internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Assert(false, "valid ParameterDirection " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
}
// IDbCommand.UpdateRowSource
internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException ConnectionStringSyntax(int index)
{
return Argument(SR.GetString(SR.ADP_ConnectionStringSyntax, index));
}
internal static ArgumentException KeywordNotSupported(string keyword)
{
return Argument(SR.GetString(SR.ADP_KeywordNotSupported, keyword));
}
internal static ArgumentException UdlFileError(Exception inner)
{
return Argument(SR.GetString(SR.ADP_UdlFileError), inner);
}
internal static ArgumentException InvalidUDL()
{
return Argument(SR.GetString(SR.ADP_InvalidUDL));
}
internal static InvalidOperationException InvalidDataDirectory()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_InvalidDataDirectory));
}
internal static ArgumentException InvalidKeyname(string parameterName)
{
return Argument(SR.GetString(SR.ADP_InvalidKey), parameterName);
}
internal static ArgumentException InvalidValue(string parameterName)
{
return Argument(SR.GetString(SR.ADP_InvalidValue), parameterName);
}
internal static ArgumentException ConvertFailed(Type fromType, Type toType, Exception innerException)
{
return ADP.Argument(SR.GetString(SR.SqlConvert_ConvertFailed, fromType.FullName, toType.FullName), innerException);
}
//
// DbConnection
//
internal static InvalidOperationException NoConnectionString()
{
return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString));
}
private static string ConnectionStateMsg(ConnectionState state)
{
switch (state)
{
case (ConnectionState.Closed):
case (ConnectionState.Connecting | ConnectionState.Broken): // treated the same as closed
return SR.GetString(SR.ADP_ConnectionStateMsg_Closed);
case (ConnectionState.Connecting):
return SR.GetString(SR.ADP_ConnectionStateMsg_Connecting);
case (ConnectionState.Open):
return SR.GetString(SR.ADP_ConnectionStateMsg_Open);
case (ConnectionState.Open | ConnectionState.Executing):
return SR.GetString(SR.ADP_ConnectionStateMsg_OpenExecuting);
case (ConnectionState.Open | ConnectionState.Fetching):
return SR.GetString(SR.ADP_ConnectionStateMsg_OpenFetching);
default:
return SR.GetString(SR.ADP_ConnectionStateMsg, state.ToString());
}
}
internal static ConfigurationException ConfigUnableToLoadXmlMetaDataFile(string settingName)
{
return Configuration(SR.GetString(SR.OleDb_ConfigUnableToLoadXmlMetaDataFile, settingName));
}
internal static ConfigurationException ConfigWrongNumberOfValues(string settingName)
{
return Configuration(SR.GetString(SR.OleDb_ConfigWrongNumberOfValues, settingName));
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValue(string key)
{
return InvalidConnectionOptionValue(key, null);
}
internal static Exception InvalidConnectionOptionValue(string key, Exception inner)
{
return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValue, key), inner);
}
//
// DbConnectionPool and related
//
internal static Exception PooledOpenTimeout()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout));
}
internal static Exception NonPooledOpenTimeout()
{
return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout));
}
//
// Generic Data Provider Collection
//
internal static ArgumentException CollectionRemoveInvalidObject(Type itemType, ICollection collection)
{
return Argument(SR.GetString(SR.ADP_CollectionRemoveInvalidObject, itemType.Name, collection.GetType().Name));
}
internal static ArgumentNullException CollectionNullValue(string parameter, Type collection, Type itemType)
{
return ArgumentNull(parameter, SR.GetString(SR.ADP_CollectionNullValue, collection.Name, itemType.Name));
}
internal static IndexOutOfRangeException CollectionIndexInt32(int index, Type collection, int count)
{
return IndexOutOfRange(SR.GetString(SR.ADP_CollectionIndexInt32, index.ToString(CultureInfo.InvariantCulture), collection.Name, count.ToString(CultureInfo.InvariantCulture)));
}
internal static IndexOutOfRangeException CollectionIndexString(Type itemType, string propertyName, string propertyValue, Type collection)
{
return IndexOutOfRange(SR.GetString(SR.ADP_CollectionIndexString, itemType.Name, propertyName, propertyValue, collection.Name));
}
internal static InvalidCastException CollectionInvalidType(Type collection, Type itemType, object invalidValue)
{
return InvalidCast(SR.GetString(SR.ADP_CollectionInvalidType, collection.Name, itemType.Name, invalidValue.GetType().Name));
}
internal static ArgumentException ParametersIsNotParent(Type parameterType, ICollection collection)
{
return Argument(SR.GetString(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
internal static ArgumentException ParametersIsParent(Type parameterType, ICollection collection)
{
return Argument(SR.GetString(SR.ADP_CollectionIsNotParent, parameterType.Name, collection.GetType().Name));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionConnectionMismatch()
{
return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch));
}
internal static InvalidOperationException TransactionRequired(string method)
{
return Provider(SR.GetString(SR.ADP_TransactionRequired, method));
}
internal static Exception CommandTextRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method));
}
internal static InvalidOperationException ConnectionRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method));
}
internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
}
internal static Exception NoStoredProcedureExists(string sproc)
{
return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
}
internal static Exception OpenReaderExists()
{
return OpenReaderExists(null);
}
internal static Exception OpenReaderExists(Exception e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
internal static Exception TransactionCompleted()
{
return DataAdapter(SR.GetString(SR.ADP_TransactionCompleted));
}
//
// DbDataReader
//
internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
}
internal static Exception NumericToDecimalOverflow()
{
return InvalidCast(SR.GetString(SR.ADP_NumericToDecimalOverflow));
}
internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception FillRequiresSourceTableName(string parameter)
{
return Argument(SR.GetString(SR.ADP_FillRequiresSourceTableName), parameter);
}
//
// : IDbCommand
//
internal static Exception InvalidCommandTimeout(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), ADP.CommandTimeout);
}
internal static Exception DeriveParametersNotSupported(IDbCommand value)
{
return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
}
internal static Exception UninitializedParameterSize(int index, Type dataType)
{
return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
}
internal static Exception PrepareParameterType(IDbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name));
}
internal static Exception PrepareParameterSize(IDbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name));
}
internal static Exception PrepareParameterScale(IDbCommand cmd, string type)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type));
}
//
// : ConnectionUtil
//
internal static Exception ClosedConnectionError()
{
return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError));
}
internal static Exception ConnectionAlreadyOpen(ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
internal static Exception TransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent));
}
internal static Exception LocalTransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent));
}
internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
}
internal static Exception EmptyDatabaseName()
{
return Argument(SR.GetString(SR.ADP_EmptyDatabaseName));
}
internal enum ConnectionError
{
BeginGetConnectionReturnsNull,
GetConnectionReturnsNull,
ConnectionOptionsMissing,
CouldNotSwitchToClosedPreviouslyOpenedState,
}
internal static Exception InternalConnectionError(ConnectionError internalError)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError));
}
internal enum InternalErrorCode
{
UnpooledObjectHasOwner = 0,
UnpooledObjectHasWrongOwner = 1,
PushingObjectSecondTime = 2,
PooledObjectHasOwner = 3,
PooledObjectInPoolMoreThanOnce = 4,
CreateObjectReturnedNull = 5,
NewObjectCannotBePooled = 6,
NonPooledObjectUsedMoreThanOnce = 7,
AttemptingToPoolOnRestrictedToken = 8,
// ConnectionOptionsInUse = 9,
ConvertSidToStringSidWReturnedNull = 10,
// UnexpectedTransactedObject = 11,
AttemptingToConstructReferenceCollectionOnStaticObject = 12,
AttemptingToEnlistTwice = 13,
CreateReferenceCollectionReturnedNull = 14,
PooledObjectWithoutPool = 15,
UnexpectedWaitAnyResult = 16,
SynchronousConnectReturnedPending = 17,
CompletedConnectReturnedPending = 18,
NameValuePairNext = 20,
InvalidParserState1 = 21,
InvalidParserState2 = 22,
InvalidParserState3 = 23,
InvalidBuffer = 30,
UnimplementedSMIMethod = 40,
InvalidSmiCall = 41,
SqlDependencyObtainProcessDispatcherFailureObjectHandle = 50,
SqlDependencyProcessDispatcherFailureCreateInstance = 51,
SqlDependencyProcessDispatcherFailureAppDomain = 52,
SqlDependencyCommandHashIsNotAssociatedWithNotification = 53,
UnknownTransactionFailure = 60,
}
internal static Exception InternalError(InternalErrorCode internalError)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalProviderError, (int)internalError));
}
internal static Exception InternalError(InternalErrorCode internalError, Exception innerException)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalProviderError, (int)internalError), innerException);
}
internal static Exception InvalidConnectTimeoutValue()
{
return Argument(SR.GetString(SR.ADP_InvalidConnectTimeoutValue));
}
//
// : DbDataReader
//
internal static Exception DataReaderNoData()
{
return InvalidOperation(SR.GetString(SR.ADP_DataReaderNoData));
}
internal static Exception DataReaderClosed(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_DataReaderClosed, method));
}
internal static ArgumentOutOfRangeException InvalidSourceBufferIndex(int maxLen, long srcOffset, string parameterName)
{
return ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidSourceBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), srcOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static ArgumentOutOfRangeException InvalidDestinationBufferIndex(int maxLen, int dstOffset, string parameterName)
{
return ArgumentOutOfRange(SR.GetString(SR.ADP_InvalidDestinationBufferIndex, maxLen.ToString(CultureInfo.InvariantCulture), dstOffset.ToString(CultureInfo.InvariantCulture)), parameterName);
}
internal static Exception InvalidDataLength(long length)
{
return IndexOutOfRange(SR.GetString(SR.SQL_InvalidDataLength, length.ToString(CultureInfo.InvariantCulture)));
}
//
// : IDataParameter
//
internal static ArgumentException InvalidDataType(TypeCode typecode)
{
return Argument(SR.GetString(SR.ADP_InvalidDataType, typecode.ToString()));
}
internal static ArgumentException DbTypeNotSupported(System.Data.DbType type, Type enumtype)
{
return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
}
internal static ArgumentException UnknownDataTypeCode(Type dataType, TypeCode typeCode)
{
return Argument(SR.GetString(SR.ADP_UnknownDataTypeCode, ((int)typeCode).ToString(CultureInfo.InvariantCulture), dataType.FullName));
}
internal static ArgumentException InvalidOffsetValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException InvalidSizeValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
{
Debug.Assert(null != value, "null value on conversion failure");
Debug.Assert(null != inner, "null inner on conversion failure");
Exception e;
string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
if (inner is ArgumentException)
{
e = new ArgumentException(message, inner);
}
else if (inner is FormatException)
{
e = new FormatException(message, inner);
}
else if (inner is InvalidCastException)
{
e = new InvalidCastException(message, inner);
}
else if (inner is OverflowException)
{
e = new OverflowException(message, inner);
}
else
{
e = inner;
}
TraceExceptionAsReturnValue(e);
return e;
}
//
// : IDataParameterCollection
//
internal static Exception ParametersMappingIndex(int index, IDataParameterCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ParametersSourceIndex(string parameterName, IDataParameterCollection collection, Type parameterType)
{
return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
}
internal static Exception ParameterNull(string parameter, IDataParameterCollection collection, Type parameterType)
{
return CollectionNullValue(parameter, collection.GetType(), parameterType);
}
internal static Exception InvalidParameterType(IDataParameterCollection collection, Type parameterType, object invalidValue)
{
return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
}
//
// : IDbTransaction
//
internal static Exception ParallelTransactionsNotSupported(IDbConnection obj)
{
return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
}
internal static Exception TransactionZombied(IDbTransaction obj)
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name));
}
//
// : DbMetaDataFactory
//
internal static Exception AmbigousCollectionName(string collectionName)
{
return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName));
}
internal static Exception CollectionNameIsNotUnique(string collectionName)
{
return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
}
internal static Exception DataTableDoesNotExist(string collectionName)
{
return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName));
}
internal static Exception IncorrectNumberOfDataSourceInformationRows()
{
return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows));
}
internal static ArgumentException InvalidRestrictionValue(string collectionName, string restrictionName, string restrictionValue)
{
return ADP.Argument(SR.GetString(SR.MDF_InvalidRestrictionValue, collectionName, restrictionName, restrictionValue));
}
internal static Exception InvalidXml()
{
return Argument(SR.GetString(SR.MDF_InvalidXml));
}
internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName));
}
internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
internal static Exception MissingDataSourceInformationColumn()
{
return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn));
}
internal static Exception MissingRestrictionColumn()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn));
}
internal static Exception MissingRestrictionRow()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionRow));
}
internal static Exception NoColumns()
{
return Argument(SR.GetString(SR.MDF_NoColumns));
}
internal static Exception QueryFailed(string collectionName, Exception e)
{
return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e);
}
internal static Exception TooManyRestrictions(string collectionName)
{
return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName));
}
internal static Exception UnableToBuildCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName));
}
internal static Exception UndefinedCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName));
}
internal static Exception UndefinedPopulationMechanism(string populationMechanism)
{
return Argument(SR.GetString(SR.MDF_UndefinedPopulationMechanism, populationMechanism));
}
internal static Exception UnsupportedVersion(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName));
}
//
// : CommandBuilder
//
internal static InvalidOperationException QuotePrefixNotSet(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_QuotePrefixNotSet, method));
}
// global constant strings
internal const string BeginTransaction = nameof(BeginTransaction);
internal const string ChangeDatabase = nameof(ChangeDatabase);
internal const string CommandTimeout = nameof(CommandTimeout);
internal const string ConnectionString = nameof(ConnectionString);
internal const string DeriveParameters = nameof(DeriveParameters);
internal const string ExecuteReader = nameof(ExecuteReader);
internal const string ExecuteNonQuery = nameof(ExecuteNonQuery);
internal const string ExecuteScalar = nameof(ExecuteScalar);
internal const string GetBytes = nameof(GetBytes);
internal const string GetChars = nameof(GetChars);
internal const string GetOleDbSchemaTable = nameof(GetOleDbSchemaTable);
internal const string GetSchema = nameof(GetSchema);
internal const string GetSchemaTable = nameof(GetSchemaTable);
internal const string Parameter = nameof(Parameter);
internal const string ParameterName = nameof(ParameterName);
internal const string Prepare = nameof(Prepare);
internal const string QuoteIdentifier = nameof(QuoteIdentifier);
internal const string SetProperties = nameof(SetProperties);
internal const string UnquoteIdentifier = nameof(UnquoteIdentifier);
internal const CompareOptions compareOptions = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
internal const int DefaultCommandTimeout = 30;
internal const int DefaultConnectionTimeout = DbConnectionStringDefaults.ConnectTimeout;
internal static readonly IntPtr PtrZero = new IntPtr(0); // IntPtr.Zero
internal static readonly int PtrSize = IntPtr.Size;
internal static readonly IntPtr RecordsUnaffected = new IntPtr(-1);
internal const int CharSize = System.Text.UnicodeEncoding.CharSize;
internal static bool CompareInsensitiveInvariant(string strvalue, string strconst)
{
return (0 == CultureInfo.InvariantCulture.CompareInfo.Compare(strvalue, strconst, CompareOptions.IgnoreCase));
}
internal static Delegate FindBuilder(MulticastDelegate mcd)
{ // V1.2.3300
if (null != mcd)
{
Delegate[] d = mcd.GetInvocationList();
for (int i = 0; i < d.Length; i++)
{
if (d[i].Target is DbCommandBuilder)
return d[i];
}
}
return null;
}
internal static readonly bool IsWindowsNT = (PlatformID.Win32NT == Environment.OSVersion.Platform);
internal static readonly bool IsPlatformNT5 = (ADP.IsWindowsNT && (Environment.OSVersion.Version.Major >= 5));
internal static SysTx.Transaction GetCurrentTransaction()
{
SysTx.Transaction transaction = SysTx.Transaction.Current;
return transaction;
}
internal static void SetCurrentTransaction(SysTx.Transaction transaction)
{
SysTx.Transaction.Current = transaction;
}
internal static SysTx.IDtcTransaction GetOletxTransaction(SysTx.Transaction transaction)
{
SysTx.IDtcTransaction oleTxTransaction = null;
if (null != transaction)
{
oleTxTransaction = SysTx.TransactionInterop.GetDtcTransaction(transaction);
}
return oleTxTransaction;
}
internal static bool NeedManualEnlistment()
{
return false;
}
internal static long TimerCurrent()
{
return DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerFromSeconds(int seconds)
{
long result = checked((long)seconds * TimeSpan.TicksPerSecond);
return result;
}
internal static long TimerRemaining(long timerExpire)
{
long timerNow = TimerCurrent();
long result = checked(timerExpire - timerNow);
return result;
}
internal static long TimerRemainingMilliseconds(long timerExpire)
{
long result = TimerToMilliseconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerToMilliseconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerMillisecond;
return result;
}
internal static string BuildQuotedString(string quotePrefix, string quoteSuffix, string unQuotedString)
{
StringBuilder resultString = new StringBuilder();
if (ADP.IsEmpty(quotePrefix) == false)
{
resultString.Append(quotePrefix);
}
// Assuming that the suffix is escaped by doubling it. i.e. foo"bar becomes "foo""bar".
if (ADP.IsEmpty(quoteSuffix) == false)
{
resultString.Append(unQuotedString.Replace(quoteSuffix, quoteSuffix + quoteSuffix));
resultString.Append(quoteSuffix);
}
else
{
resultString.Append(unQuotedString);
}
return resultString.ToString();
}
internal static void EscapeSpecialCharacters(string unescapedString, StringBuilder escapedString)
{
// note special characters list is from character escapes
// in the MSDN regular expression language elements documentation
// added ] since escaping it seems necessary
const string specialCharacters = ".$^{[(|)*+?\\]";
foreach (char currentChar in unescapedString)
{
if (specialCharacters.IndexOf(currentChar) >= 0)
{
escapedString.Append("\\");
}
escapedString.Append(currentChar);
}
return;
}
internal static string GetFullPath(string filename)
{
return Path.GetFullPath(filename);
}
// SxS: the file is opened in FileShare.Read mode allowing several threads/apps to read it simultaneously
internal static Stream GetFileStream(string filename)
{
return new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
}
internal static FileVersionInfo GetVersionInfo(string filename)
{
return FileVersionInfo.GetVersionInfo(filename);
}
internal static Stream GetXmlStreamFromValues(string[] values, string errorString)
{
if (values.Length != 1)
{
throw ADP.ConfigWrongNumberOfValues(errorString);
}
return ADP.GetXmlStream(values[0], errorString);
}
// metadata files are opened from <.NetRuntimeFolder>\CONFIG\<metadatafilename.xml>
// this operation is safe in SxS because the file is opened in read-only mode and each NDP runtime accesses its own copy of the metadata
// under the runtime folder.
internal static Stream GetXmlStream(string value, string errorString)
{
Stream XmlStream;
const string config = "config\\";
// get location of config directory
string rootPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
if (rootPath == null)
{
throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
}
StringBuilder tempstring = new StringBuilder(rootPath.Length + config.Length + value.Length);
tempstring.Append(rootPath);
tempstring.Append(config);
tempstring.Append(value);
string fullPath = tempstring.ToString();
// don't allow relative paths
if (ADP.GetFullPath(fullPath) != fullPath)
{
throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
}
try
{
XmlStream = ADP.GetFileStream(fullPath);
}
catch (Exception e)
{
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.ConfigUnableToLoadXmlMetaDataFile(errorString);
}
return XmlStream;
}
internal static object ClassesRootRegistryValue(string subkey, string queryvalue)
{
try
{
using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(subkey, false))
{
return ((null != key) ? key.GetValue(queryvalue) : null);
}
}
catch (SecurityException e)
{
// it's possible there are
// ACL's on registry that cause SecurityException to be thrown.
ADP.TraceExceptionWithoutRethrow(e);
return null;
}
}
internal static object LocalMachineRegistryValue(string subkey, string queryvalue)
{
try
{
using (RegistryKey key = Registry.LocalMachine.OpenSubKey(subkey, false))
{
return ((null != key) ? key.GetValue(queryvalue) : null);
}
}
catch (SecurityException e)
{
// it's possible there are
// ACL's on registry that cause SecurityException to be thrown.
ADP.TraceExceptionWithoutRethrow(e);
return null;
}
}
// SxS: although this method uses registry, it does not expose anything out
internal static void CheckVersionMDAC(bool ifodbcelseoledb)
{
int major, minor, build;
string version;
try
{
version = (string)ADP.LocalMachineRegistryValue("Software\\Microsoft\\DataAccess", "FullInstallVer");
if (ADP.IsEmpty(version))
{
string filename = (string)ADP.ClassesRootRegistryValue(System.Data.OleDb.ODB.DataLinks_CLSID, string.Empty);
FileVersionInfo versionInfo = ADP.GetVersionInfo(filename);
major = versionInfo.FileMajorPart;
minor = versionInfo.FileMinorPart;
build = versionInfo.FileBuildPart;
version = versionInfo.FileVersion;
}
else
{
string[] parts = version.Split('.');
major = int.Parse(parts[0], NumberStyles.None, CultureInfo.InvariantCulture);
minor = int.Parse(parts[1], NumberStyles.None, CultureInfo.InvariantCulture);
build = int.Parse(parts[2], NumberStyles.None, CultureInfo.InvariantCulture);
int.Parse(parts[3], NumberStyles.None, CultureInfo.InvariantCulture);
}
}
catch (Exception e)
{
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw System.Data.OleDb.ODB.MDACNotAvailable(e);
}
// disallow any MDAC version before MDAC 2.6 rtm
// include MDAC 2.51 that ships with Win2k
if ((major < 2) || ((major == 2) && ((minor < 60) || ((minor == 60) && (build < 6526)))))
{
if (ifodbcelseoledb)
{
throw ADP.DataAdapter(SR.GetString(SR.Odbc_MDACWrongVersion, version));
}
else
{
throw ADP.DataAdapter(SR.GetString(SR.OleDb_MDACWrongVersion, version));
}
}
}
// the return value is true if the string was quoted and false if it was not
// this allows the caller to determine if it is an error or not for the quotedString to not be quoted
internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString)
{
int prefixLength;
if (quotePrefix == null)
{
prefixLength = 0;
}
else
{
prefixLength = quotePrefix.Length;
}
int suffixLength;
if (quoteSuffix == null)
{
suffixLength = 0;
}
else
{
suffixLength = quoteSuffix.Length;
}
if ((suffixLength + prefixLength) == 0)
{
unquotedString = quotedString;
return true;
}
if (quotedString == null)
{
unquotedString = quotedString;
return false;
}
int quotedStringLength = quotedString.Length;
// is the source string too short to be quoted
if (quotedStringLength < prefixLength + suffixLength)
{
unquotedString = quotedString;
return false;
}
// is the prefix present?
if (prefixLength > 0)
{
if (quotedString.StartsWith(quotePrefix, StringComparison.Ordinal) == false)
{
unquotedString = quotedString;
return false;
}
}
// is the suffix present?
if (suffixLength > 0)
{
if (quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal) == false)
{
unquotedString = quotedString;
return false;
}
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix);
}
else
{
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength);
}
return true;
}
internal static IntPtr IntPtrOffset(IntPtr pbase, int offset)
{
if (4 == ADP.PtrSize)
{
return (IntPtr)checked(pbase.ToInt32() + offset);
}
Debug.Assert(8 == ADP.PtrSize, "8 != IntPtr.Size");
return (IntPtr)checked(pbase.ToInt64() + offset);
}
internal static int IntPtrToInt32(IntPtr value)
{
if (4 == ADP.PtrSize)
{
return (int)value;
}
else
{
long lval = (long)value;
lval = Math.Min((long)int.MaxValue, lval);
lval = Math.Max((long)int.MinValue, lval);
return (int)lval;
}
}
// TODO: are those names appropriate for common code?
internal static int SrcCompare(string strA, string strB)
{ // this is null safe
return ((strA == strB) ? 0 : 1);
}
internal static int DstCompare(string strA, string strB)
{ // this is null safe
return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, ADP.compareOptions);
}
internal static bool IsDirection(IDataParameter value, ParameterDirection condition)
{
#if DEBUG
IsDirectionValid(condition);
#endif
return (condition == (condition & value.Direction));
}
#if DEBUG
private static void IsDirectionValid(ParameterDirection value)
{
switch (value)
{ // @perfnote: Enum.IsDefined
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
#endif
internal static bool IsEmpty(string str)
{
return ((null == str) || (0 == str.Length));
}
internal static bool IsEmptyArray(string[] array)
{
return ((null == array) || (0 == array.Length));
}
internal static bool IsNull(object value)
{
if ((null == value) || (DBNull.Value == value))
{
return true;
}
INullable nullable = (value as INullable);
return ((null != nullable) && nullable.IsNull);
}
}
}
| |
using System;
using System.Collections.Generic;
using VacationMasters.Essentials;
using VacationMasters.UserManagement;
using VacationMasters.Wrappers;
using System.Linq;
namespace VacationMasters.PackageManagement
{
public class PackageManager
{
private readonly IDbWrapper _dbWrapper;
private readonly IUserManager _userManager;
public PackageManager(IDbWrapper dbWrapper)
{
_dbWrapper = dbWrapper;
_userManager = new UserManager(_dbWrapper);
}
public List<Package> SearchPackages(string searchQuery)
{
List<Package> searchedPackages = new List<Package>();
var packagesByName = _dbWrapper.GetPackagesByName(searchQuery);
var packagesByType = _dbWrapper.getPackagesByType(searchQuery);
if (packagesByName != null)
searchedPackages.AddRange(packagesByName);
if (packagesByType != null)
searchedPackages.AddRange(packagesByType);
return searchedPackages;
}
public void AddPackage(Package package)
{
var sql = string.Format("INSERT INTO Packages(Name, Type, Included, Transport, Price, SearchIndex, Rating,"
+ "BeginDate, EndDate, Picture,TotalVotes) "
+ "VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', {6}, '{7}', '{8}', '{9}','0');",
package.Name, package.Type, package.Included, package.Transport, package.Price,
package.SearchIndex, package.Rating, package.BeginDate.ToString("yyyy-MM-dd HH:mm:ss"), package.EndDate.ToString("yyyy-MM-dd HH:mm:ss"), package.Picture);
_dbWrapper.QueryValue<object>(sql);
}
public void Display(List<Package> l)
{
var list = l;
foreach (Package pack in list)
{
}
}
public void RemovePackage(Package package)
{
var sql = string.Format("Delete From ChoosePackage Where IDPackage = {0}; DELETE FROM Packages WHERE ID = {0}; ", package.ID);
_dbWrapper.QueryValue<object>(sql);
}
public List<Package> GetPackagesByPreferences()
{
User loggedUser = UserManager.CurrentUser;
List<Package> packagesByPrefrences = new List<Package>();
var destinations = _userManager.GetStrings("Select Name From Destinations");
var destMatched = new List<string>();
var results = new List<Package>();
foreach (var pref in loggedUser.Preferences)
{
if (destinations.Contains(pref.Name))
{
destMatched.Add(pref.Name);
}
}
foreach (var dest in destMatched)
{
var sql = string.Format("Select p.ID,p.Name,p.Type,p.Included,p.Transport,p.Price,p.SearchIndex,p.Rating,p.BeginDate,p.EndDate,p.Picture from packages p join ChooseDestinations cd on (p.ID = cd.IDPackage)" +
" join destinations d on (cd.IDDestination = d.ID) where d.Name = '{0}';", dest);
results = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadPackages(command);
});
}
foreach (var item in results)
packagesByPrefrences.Add(item);
var sortedPackagesByPrefrences = packagesByPrefrences.OrderBy(p => p.Rating).ThenBy(p => p.SearchIndex).ToList<Package>();
return sortedPackagesByPrefrences;
}
public List<Package> GetPackagesByHistoric()
{
User loggedUser = UserManager.CurrentUser;
List<Package> packagesByHistoric = new List<Package>();
string sql = string.Format("Select p.ID,p.Name,p.Type,p.Included,p.Transport,p.Price,p.SearchIndex,p.Rating,p.BeginDate,p.EndDate,p.Picture from packages p join choosepackage cp on (p.ID = cp.IDPackage)" +
" join Orders o on (cp.IDOrder = o.ID) join Users u on (u.ID = o.IDUser) Where u.UserName = '{0}'", loggedUser.UserName);
List<Package> results = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadPackages(command);
});
var typeList = results.Select(p => p.Type);
foreach (var res in results)
{
sql = string.Format("Select d.Name from destinations d join ChooseDestinations cd on (cd.IDDestination = d.ID)" +
" join packages p on (p.ID = cd.IDPackage) where p.ID = {0};", res.ID);
var results2 = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadDestinationName(command);
});
foreach (var dest in results2)
{
sql = string.Format("Select * from Packages p join ChooseDestinations cd on (p.ID = cd.IDPackage) " +
" join Destinations d on (cd.IDDestination = d.ID) WHERE d.Name = '{0}'", dest);
}
var packAtDest = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadPackages(command);
});
foreach (Package pack in packAtDest)
packagesByHistoric.Add(pack);
}
var nameList = packagesByHistoric.Select(p => p.Name);
List<int> frequencyNameArray = new List<int>();
foreach (var name in nameList)
frequencyNameArray.Add(nameList.Count(nume => nume == name));
List<int> frequencyTypeArray = new List<int>();
foreach (var type in typeList)
frequencyTypeArray.Add(typeList.Count(tip => tip == type));
int index = 0;
foreach (var i in frequencyTypeArray)
if (i == frequencyTypeArray.Max())
index = frequencyTypeArray.IndexOf(i);
var typeMax = string.Empty;
if(typeList.Count()>0)
typeList.ElementAt(index);
foreach (var i in frequencyNameArray)
if (i == frequencyNameArray.Max())
index = frequencyNameArray.IndexOf(i);
var nameMax = string.Empty;
if(nameList.Count()>0)
nameMax = nameList.ElementAt(index);
sql = string.Format("Select Distinct p.ID,p.Name,p.Type,p.Included,p.Transport,p.Price,p.SearchIndex,p.Rating,p.BeginDate,p.EndDate,p.Picture from preferences d join ChooseDestinations cd on (cd.IDDestination = d.ID)" +
" join packages p on (p.ID = cd.IDPackage) where p.Type = '{0}' or d.Name = '{1}';", typeMax, nameMax);
var selectedPackages = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadPackages(command);
});
var selected2Packages = RemoveDuplicated(selectedPackages, results);
selected2Packages.OrderBy(p => p.Rating).ThenBy(p => p.SearchIndex);
return selected2Packages;
}
public List<Package> GetPackagesByUserGroups()
{
User loggedUser = UserManager.CurrentUser;
var packagesByUserGroups = new List<Package>();
var sql = string.Format("Select Name from Groups g join ChooseGroups cg on (g.ID = cg.IDGroup)" +
" join Users u on (u.ID = cg.IDUser) where u.UserName = '{0}'", loggedUser.UserName);
var groups = new List<String>();
groups = _userManager.GetStrings(sql);
var users = new List<String>();
foreach (var group in groups)
{
sql = string.Format("Select u.ID from Users u join ChooseGroups cg on (u.ID = cg.IDUser)" +
" join Groups g on (g.ID = cg.IDGroup) where Name = '{0}'", group);
var temp = new List<String>();
temp = _userManager.GetStrings(sql);
users.AddRange(temp);
}
foreach (var user in users)
{
sql = string.Format("Select p.ID,p.Name,p.Type,p.Included,p.Transport,p.Price,p.SearchIndex,p.Rating,p.BeginDate,p.EndDate,p.Picture from Packages p join ChoosePackage cp on (p.ID = cp.IDPackage)" +
" join Orders o on (o.ID = cp.IDOrder) join Users u on " +
" (u.ID = o.IDUser) where u.ID = {0}", user);
var temp = new List<Package>();
temp = _dbWrapper.RunCommand(command =>
{
command.CommandText = sql;
return _dbWrapper.ReadPackages(command);
});
packagesByUserGroups = RemoveDuplicated(packagesByUserGroups,
temp);
}
var noduplicatespackagesByUserGroups = packagesByUserGroups;
return noduplicatespackagesByUserGroups;
}
public List<Package> GetPackagesByRecommendation()
{
var listByPreferences = GetPackagesByPreferences();
var listByHistoric = GetPackagesByHistoric();
var listByUserGroups = GetPackagesByUserGroups();
var noDuplicatesFinalList = RemoveDuplicated(listByPreferences, listByUserGroups);
var noDups = RemoveDuplicated(noDuplicatesFinalList, listByHistoric);
var relevantList = noDups.OrderByDescending(p => p.Rating).ThenByDescending(p => p.SearchIndex).ToList();
var rest = _dbWrapper.getRandomPackages().OrderByDescending(p=>p.Rating).ToList();
return RemoveDuplicated(relevantList, rest);
}
private static List<Package> RemoveDuplicated(List<Package> relevantList, List<Package> rest)
{
var finalList = new List<Package>();
finalList.AddRange(relevantList);
foreach (var item in rest)
{
var isDuplicated = false;
foreach (var item2 in relevantList)
{
if (item2.ID == item.ID)
isDuplicated = true;
}
if (isDuplicated == false) finalList.Add(item);
}
return finalList;
}
public int CheckIfUserHasOrderedThePackage(int packageId, string userName)
{
var sql = string.Format("SELECT o.Id FROM Users u JOIN Orders o ON (u.ID = o.IDUser) JOIN ChoosePackage c ON (o.ID = c.IDOrder) Where c.IDPackage = {0} AND u.UserName= '{1}' ", packageId, userName);
return _dbWrapper.QueryValue<int>(sql);
}
public bool CheckIfUserDidVote(int packageId, string userName)
{
var sql = string.Format("SELECT c.HasRated FROM Users u JOIN Orders o ON (u.ID = o.IDUser) JOIN ChoosePackage c ON (o.ID = c.IDOrder) Where c.IDPackage = {0} AND u.UserName= '{1}' ", packageId, userName);
return _dbWrapper.QueryValue<bool>(sql);
}
public int RetrieveUserId(string userName)
{
var sql = string.Format("Select ID From Users Where UserName = '{0}';", userName);
return _dbWrapper.QueryValue<int>(sql);
}
public void ReservePackage(string userName, DateTime now, double price, int id)
{
var userId = RetrieveUserId(userName);
var sql = string.Format("INSERT INTO Orders(IDUser,Status, Date , TotalPrice)" +
"values('{0}', '{1}', '{2}', '{3}');", userId, "Reserved", now.ToString("yyyy-MM-dd HH:mm:ss"), price);
sql += "SELECT LAST_INSERT_ID();";
var idOrder = _dbWrapper.QueryValue<int>(sql);
sql = string.Format("INSERT INTO ChoosePackage(IDOrder,IDPackage,HasRated) values('{0}','{1}','0');", idOrder, id);
_dbWrapper.QueryValue<object>(sql);
}
public void CancelReservation(int packageId, int orderId)
{
var sql = string.Format("DELETE FROM ChoosePackage" +
" WHERE IDPackage = {0} AND IDOrder = {1};", packageId, orderId);
sql += string.Format("Delete from Orders where ID = '{0}';", orderId);
_dbWrapper.QueryValue<object>(sql);
}
public void UpdateRating(int packageId, double rating, int orderId)
{
var sql = string.Format("UPDATE Packages" + " SET Rating = (Rating*TotalVotes+{1})/(TotalVotes+1)" +
" WHERE Id = {0};" + " UPDATE Packages SET TotalVotes = TotalVotes + 1 Where Id={0}; " + "UPDATE ChoosePackage SET HasRated = 1 Where IDPackage = {0} And IDOrder = {2}; ", packageId, rating, orderId);
_dbWrapper.QueryValue<object>(sql);
}
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Diagnostics.CodeAnalysis;
namespace WeifenLuo.WinFormsUI.Docking
{
public class FloatWindow : Form, INestedPanesContainer, IDockDragSource
{
private NestedPaneCollection m_nestedPanes;
internal const int WM_CHECKDISPOSE = (int)(Win32.Msgs.WM_USER + 1);
internal protected FloatWindow(DockPanel dockPanel, DockPane pane)
{
InternalConstruct(dockPanel, pane, false, Rectangle.Empty);
}
internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds)
{
InternalConstruct(dockPanel, pane, true, bounds);
}
private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds)
{
if (dockPanel == null)
throw(new ArgumentNullException(Strings.FloatWindow_Constructor_NullDockPanel));
m_nestedPanes = new NestedPaneCollection(this);
FormBorderStyle = FormBorderStyle.SizableToolWindow;
ShowInTaskbar = false;
if (dockPanel.RightToLeft != RightToLeft)
RightToLeft = dockPanel.RightToLeft;
if (RightToLeftLayout != dockPanel.RightToLeftLayout)
RightToLeftLayout = dockPanel.RightToLeftLayout;
SuspendLayout();
if (boundsSpecified)
{
Bounds = bounds;
StartPosition = FormStartPosition.Manual;
}
else
{
StartPosition = FormStartPosition.WindowsDefaultLocation;
Size = dockPanel.DefaultFloatWindowSize;
}
m_dockPanel = dockPanel;
Owner = DockPanel.FindForm();
DockPanel.AddFloatWindow(this);
if (pane != null)
pane.FloatWindow = this;
ResumeLayout();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (DockPanel != null)
DockPanel.RemoveFloatWindow(this);
m_dockPanel = null;
}
base.Dispose(disposing);
}
private bool m_allowEndUserDocking = true;
public bool AllowEndUserDocking
{
get { return m_allowEndUserDocking; }
set { m_allowEndUserDocking = value; }
}
public NestedPaneCollection NestedPanes
{
get { return m_nestedPanes; }
}
public VisibleNestedPaneCollection VisibleNestedPanes
{
get { return NestedPanes.VisibleNestedPanes; }
}
private DockPanel m_dockPanel;
public DockPanel DockPanel
{
get { return m_dockPanel; }
}
public DockState DockState
{
get { return DockState.Float; }
}
public bool IsFloat
{
get { return DockState == DockState.Float; }
}
internal bool IsDockStateValid(DockState dockState)
{
foreach (DockPane pane in NestedPanes)
foreach (IDockContent content in pane.Contents)
if (!DockHelper.IsDockStateValid(dockState, content.DockHandler.DockAreas))
return false;
return true;
}
protected override void OnActivated(EventArgs e)
{
DockPanel.FloatWindows.BringWindowToFront(this);
base.OnActivated (e);
}
protected override void OnLayout(LayoutEventArgs levent)
{
VisibleNestedPanes.Refresh();
RefreshChanges();
Visible = (VisibleNestedPanes.Count > 0);
SetText();
base.OnLayout(levent);
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")]
internal void SetText()
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane == null)
Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false.
else if (theOnlyPane.ActiveContent == null)
Text = " ";
else
Text = theOnlyPane.ActiveContent.DockHandler.TabText;
}
protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
Rectangle rectWorkArea = SystemInformation.VirtualScreen;
if (y + height > rectWorkArea.Bottom)
y -= (y + height) - rectWorkArea.Bottom;
if (y < rectWorkArea.Top)
y += rectWorkArea.Top - y;
base.SetBoundsCore (x, y, width, height, specified);
}
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDOWN)
{
if (IsDisposed)
return;
uint result = NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2 && DockPanel.AllowEndUserDocking && this.AllowEndUserDocking) // HITTEST_CAPTION
{
Activate();
m_dockPanel.BeginDrag(this);
}
else
base.WndProc(ref m);
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCRBUTTONDOWN)
{
uint result = NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result == 2) // HITTEST_CAPTION
{
DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null;
if (theOnlyPane != null && theOnlyPane.ActiveContent != null)
{
theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition));
return;
}
}
base.WndProc(ref m);
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_CLOSE)
{
if (NestedPanes.Count == 0)
{
base.WndProc(ref m);
return;
}
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockContentCollection contents = NestedPanes[i].Contents;
for (int j = contents.Count - 1; j >= 0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (!content.DockHandler.CloseButton)
continue;
if (content.DockHandler.HideOnClose)
content.DockHandler.Hide();
else
content.DockHandler.Close();
}
}
return;
}
else if (m.Msg == (int)Win32.Msgs.WM_NCLBUTTONDBLCLK)
{
uint result = NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam);
if (result != 2) // HITTEST_CAPTION
{
base.WndProc(ref m);
return;
}
DockPanel.SuspendLayout(true);
// Restore to panel
foreach (DockPane pane in NestedPanes)
{
if (pane.DockState != DockState.Float)
continue;
pane.RestoreToPanel();
}
DockPanel.ResumeLayout(true, true);
return;
}
else if (m.Msg == WM_CHECKDISPOSE)
{
if (NestedPanes.Count == 0)
Dispose();
return;
}
base.WndProc(ref m);
}
internal void RefreshChanges()
{
if (IsDisposed)
return;
if (VisibleNestedPanes.Count == 0)
{
ControlBox = true;
return;
}
for (int i=VisibleNestedPanes.Count - 1; i>=0; i--)
{
DockContentCollection contents = VisibleNestedPanes[i].Contents;
for (int j=contents.Count - 1; j>=0; j--)
{
IDockContent content = contents[j];
if (content.DockHandler.DockState != DockState.Float)
continue;
if (content.DockHandler.CloseButton)
{
ControlBox = true;
return;
}
}
}
ControlBox = false;
}
public virtual Rectangle DisplayingRectangle
{
get { return ClientRectangle; }
}
internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
{
if (VisibleNestedPanes.Count == 1)
{
DockPane pane = VisibleNestedPanes[0];
if (!dragSource.CanDockTo(pane))
return;
Point ptMouse = Control.MousePosition;
uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y);
if (NativeMethods.SendMessage(Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, lParam) == (uint)Win32.HitTest.HTCAPTION)
dockOutline.Show(VisibleNestedPanes[0], -1);
}
}
#region IDockDragSource Members
#region IDragSource Members
Control IDragSource.DragControl
{
get { return this; }
}
#endregion
bool IDockDragSource.IsDockStateValid(DockState dockState)
{
return IsDockStateValid(dockState);
}
bool IDockDragSource.CanDockTo(DockPane pane)
{
if (!IsDockStateValid(pane.DockState))
return false;
if (pane.FloatWindow == this)
return false;
return true;
}
Rectangle IDockDragSource.BeginDrag(Point ptMouse)
{
return Bounds;
}
public void FloatAt(Rectangle floatWindowBounds)
{
Bounds = floatWindowBounds;
}
public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
{
if (dockStyle == DockStyle.Fill)
{
for (int i = NestedPanes.Count - 1; i >= 0; i--)
{
DockPane paneFrom = NestedPanes[i];
for (int j = paneFrom.Contents.Count - 1; j >= 0; j--)
{
IDockContent c = paneFrom.Contents[j];
c.DockHandler.Pane = pane;
if (contentIndex != -1)
pane.SetContentIndex(c, contentIndex);
}
}
}
else
{
DockAlignment alignment = DockAlignment.Left;
if (dockStyle == DockStyle.Left)
alignment = DockAlignment.Left;
else if (dockStyle == DockStyle.Right)
alignment = DockAlignment.Right;
else if (dockStyle == DockStyle.Top)
alignment = DockAlignment.Top;
else if (dockStyle == DockStyle.Bottom)
alignment = DockAlignment.Bottom;
MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5);
}
}
public void DockTo(DockPanel panel, DockStyle dockStyle)
{
if (panel != DockPanel)
throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");
NestedPaneCollection nestedPanesTo = null;
if (dockStyle == DockStyle.Top)
nestedPanesTo = DockPanel.DockWindows[DockState.DockTop].NestedPanes;
else if (dockStyle == DockStyle.Bottom)
nestedPanesTo = DockPanel.DockWindows[DockState.DockBottom].NestedPanes;
else if (dockStyle == DockStyle.Left)
nestedPanesTo = DockPanel.DockWindows[DockState.DockLeft].NestedPanes;
else if (dockStyle == DockStyle.Right)
nestedPanesTo = DockPanel.DockWindows[DockState.DockRight].NestedPanes;
else if (dockStyle == DockStyle.Fill)
nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes;
DockPane prevPane = null;
for (int i = nestedPanesTo.Count - 1; i >= 0; i--)
if (nestedPanesTo[i] != VisibleNestedPanes[0])
prevPane = nestedPanesTo[i];
MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5);
}
private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion)
{
if (nestedPanesFrom.Count == 0)
return;
int count = nestedPanesFrom.Count;
DockPane[] panes = new DockPane[count];
DockPane[] prevPanes = new DockPane[count];
DockAlignment[] alignments = new DockAlignment[count];
double[] proportions = new double[count];
for (int i = 0; i < count; i++)
{
panes[i] = nestedPanesFrom[i];
prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane;
alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment;
proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion;
}
DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion);
panes[0].DockState = nestedPanesTo.DockState;
for (int i = 1; i < count; i++)
{
for (int j = i; j < count; j++)
{
if (prevPanes[j] == panes[i - 1])
prevPanes[j] = pane;
}
pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]);
panes[i].DockState = nestedPanesTo.DockState;
}
}
#endregion
private void InitializeComponent()
{
this.SuspendLayout();
//
// FloatWindow
//
this.ClientSize = new System.Drawing.Size(292, 273);
this.KeyPreview = true;
this.Name = "FloatWindow";
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.FloatWindow_KeyUp);
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FloatWindow_KeyDown);
this.ResumeLayout(false);
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (base.ProcessCmdKey(ref msg, keyData))
return true;
else
return DockPanel.ForwardCmdKey(ref msg, keyData);
}
private void FloatWindow_KeyDown(object sender, KeyEventArgs e)
{
if (ToolStripManager.IsShortcutDefined(e.KeyData))
MessageBox.Show("Shortcut entered: " + e.KeyData.ToString());
}
private void FloatWindow_KeyUp(object sender, KeyEventArgs e)
{
if (ToolStripManager.IsShortcutDefined(e.KeyData))
MessageBox.Show("Shortcut entered: " + e.KeyData.ToString());
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.15.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.TrafficManager
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// EndpointsOperations operations.
/// </summary>
internal partial class EndpointsOperations : IServiceOperations<TrafficManagerManagementClient>, IEndpointsOperations
{
/// <summary>
/// Initializes a new instance of the EndpointsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal EndpointsOperations(TrafficManagerManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the TrafficManagerManagementClient
/// </summary>
public TrafficManagerManagementClient Client { get; private set; }
/// <summary>
/// Update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the Update operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> UpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> GetWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create or update a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be created or updated.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be created or updated.
/// </param>
/// <param name='parameters'>
/// The Traffic Manager endpoint parameters supplied to the CreateOrUpdate
/// operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<Endpoint>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Endpoint parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<Endpoint>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Endpoint>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes a Traffic Manager endpoint.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group containing the Traffic Manager endpoint to
/// be deleted.
/// </param>
/// <param name='profileName'>
/// The name of the Traffic Manager profile.
/// </param>
/// <param name='endpointType'>
/// The type of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='endpointName'>
/// The name of the Traffic Manager endpoint to be deleted.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string profileName, string endpointType, string endpointName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (profileName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "profileName");
}
if (endpointType == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointType");
}
if (endpointName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "endpointName");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("profileName", profileName);
tracingParameters.Add("endpointType", endpointType);
tracingParameters.Add("endpointName", endpointName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/trafficmanagerprofiles/{profileName}/{endpointType}/{endpointName}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{profileName}", Uri.EscapeDataString(profileName));
_url = _url.Replace("{endpointType}", Uri.EscapeDataString(endpointType));
_url = _url.Replace("{endpointName}", Uri.EscapeDataString(endpointName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Vevo;
using Vevo.Domain;
using Vevo.Domain.Products;
using Vevo.Domain.Stores;
using Vevo.Shared.DataAccess;
public partial class Admin_Components_StoreConfig_StoreDisplayConfig : AdminAdvancedBaseUserControl
{
private Store CurrentStore
{
get
{
return DataAccessContext.StoreRepository.GetOne( StoreID );
}
}
private string LanguageID
{
get
{
return AdminConfig.CurrentContentCultureID;
}
}
private void SetUpRootCategoryDropDown()
{
uxRootCategoryDrop.Items.Clear();
Culture culture = DataAccessContext.CultureRepository.GetOne( LanguageID );
IList<Category> rootCategoryList =
DataAccessContext.CategoryRepository.GetRootCategory( culture, "CategoryID", BoolFilter.ShowAll );
foreach (Category rootCategory in rootCategoryList)
{
uxRootCategoryDrop.Items.Add( new ListItem( rootCategory.Name, rootCategory.CategoryID ) );
}
uxRootCategoryDrop.SelectedValue = DataAccessContext.Configurations.GetValueNoThrow( "RootCategory", CurrentStore );
}
private void SetUpRootDepartmentDropDown()
{
uxRootDepartmentDrop.Items.Clear();
Culture culture = DataAccessContext.CultureRepository.GetOne( LanguageID );
IList<Department> rootDepartmentList =
DataAccessContext.DepartmentRepository.GetRootDepartment( culture, "DepartmentID", BoolFilter.ShowAll );
if (rootDepartmentList.Count > 0)
{
foreach (Department rootDepartment in rootDepartmentList)
{
uxRootDepartmentDrop.Items.Add( new ListItem( rootDepartment.Name, rootDepartment.DepartmentID ) );
}
uxRootDepartmentDrop.SelectedValue = DataAccessContext.Configurations.GetValueNoThrow( "RootDepartment", CurrentStore );
}
else
{
if (KeyUtilities.IsMultistoreLicense())
uxRootDepartmentDrop.Items.Add( new ListItem( "None", "0" ) );
else
uxRootDepartmentDrop.Items.Add( new ListItem( "None", "1" ) );
uxRootDepartmentDrop.Enabled = false;
}
}
protected void Page_Load( object sender, EventArgs e )
{
if (MainContext.IsPostBack)
{
uxThemeSelect.PopulateControls();
uxMobileThemeSelect.PopulateControls();
uxCategorySelect.PopulateControls();
uxDepartmentSelect.PopulateControls();
uxProductListSelect.PopulateControls();
uxProductDetailsSelect.PopulateControls();
uxGoogleAnalyticsConfig.PopulateControls(CurrentStore);
}
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!MainContext.IsPostBack)
PopulateControls();
}
public void PopulateControls()
{
uxSiteName.CultureID = LanguageID;
uxSiteName.PopulateControl();
uxLogoImage.PopulateControls();
uxDefaultwebsiteLanguage.PopulateControls();
uxStoreDefaultCountryDropDown.CurrentSelected
= DataAccessContext.Configurations.GetValue( "StoreDefaultCountry", CurrentStore ).ToString();
uxSearchModeDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "SearchMode", CurrentStore ).ToString();
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxBundlePromotionShowTR.Visible = false;
uxBundlePromotionShowText.Text = "0";
uxBundlePromotionShowText.Enabled = false;
}
else
{
uxBundlePromotionShowText.Text = DataAccessContext.Configurations.GetValue( "BundlePromotionShow", CurrentStore ).ToString();
}
uxRandomNumberText.Text = DataAccessContext.Configurations.GetValue( "RandomProductShow", CurrentStore );
uxNumberBestSelling.Text
= DataAccessContext.Configurations.GetValue( "ProductBestSellingShow", CurrentStore );
SetUpRootCategoryDropDown();
SetUpRootDepartmentDropDown();
uxCategoryMenuTypeDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "CategoryMenuType", CurrentStore ).ToString();
uxDepartmentMenuTypeDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "DepartmentMenuType", CurrentStore ).ToString();
uxCategoryMenuLevelText.Text
= DataAccessContext.Configurations.GetValue( "CategoryMenuLevel", CurrentStore );
uxDepartmentMenuLevelText.Text
= DataAccessContext.Configurations.GetValue( "DepartmentMenuLevel", CurrentStore );
uxCategoryDynamicDropDownDisplayDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "CategoryDynamicDropDownDisplay", CurrentStore );
uxDepartmentDynamicDropDownDisplayDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "DepartmentDynamicDropDownDisplay", CurrentStore );
uxManufacturerDynamicDropDownDisplayDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "ManufacturerDynamicDropDownDisplay", CurrentStore );
uxCategoryDynamicDropDownLevelText.Text
= DataAccessContext.Configurations.GetValue( "CategoryDynamicDropDownLevel", CurrentStore );
uxDepartmentDynamicDropDownLevelText.Text
= DataAccessContext.Configurations.GetValue( "DepartmentDynamicDropDownLevel", CurrentStore );
uxCategoryShowProductListDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "CategoryShowProductList", CurrentStore ).ToString();
uxDepartmentShowProductListDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "DepartmentShowProductList", CurrentStore ).ToString();
uxThemeSelect.PopulateControls( CurrentStore );
uxMobileThemeSelect.PopulateControls( CurrentStore );
uxCategorySelect.PopulateControls( CurrentStore );
uxDepartmentSelect.PopulateControls( CurrentStore );
uxProductListSelect.PopulateControls( CurrentStore );
uxProductDetailsSelect.PopulateControls( CurrentStore );
//uxDefaultMobileThemeSelect.PopulateControls( CurrentStore );
uxNumberOfProduct.Text
= DataAccessContext.Configurations.GetValue( "ProductItemsPerPage", CurrentStore );
uxNumberOfCategory.Text
= DataAccessContext.Configurations.GetValue( "CategoryItemsPerPage", CurrentStore );
uxNumberOfDepartment.Text
= DataAccessContext.Configurations.GetValue( "DepartmentItemsPerPage", CurrentStore );
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxBundlePromotionDisplayTR.Visible = false;
uxBundlePromotionDisplayText.Text = "0";
uxBundlePromotionDisplayText.Enabled = false;
}
else
{
uxBundlePromotionDisplayText.Text
= DataAccessContext.Configurations.GetValue( "BundlePromotionDisplay", CurrentStore );
}
uxNumberOfProductColumnText.Text
= DataAccessContext.Configurations.GetValue( "NumberOfProductColumn", CurrentStore );
uxNumberOfCategoryColumnText.Text
= DataAccessContext.Configurations.GetValue( "NumberOfCategoryColumn", CurrentStore );
uxNumberOfDepartmentColumnText.Text
= DataAccessContext.Configurations.GetValue( "NumberOfDepartmentColumn", CurrentStore );
if (!KeyUtilities.IsDeluxeLicense( DataAccessHelper.DomainRegistrationkey, DataAccessHelper.DomainName ))
{
uxBundlePromotionColumnTR.Visible = false;
uxBundlePromotionColumnText.Text = "0";
uxBundlePromotionColumnText.Enabled = false;
}
else
{
uxBundlePromotionColumnText.Text
= DataAccessContext.Configurations.GetValue( "BundlePromotionColumn", CurrentStore );
}
uxNumberRecentlyViewed.Text
= DataAccessContext.Configurations.GetValue( "RecentlyViewedProductShow", CurrentStore );
uxNumberCompareProduct.Text
= DataAccessContext.Configurations.GetValue( "CompareProductShow", CurrentStore );
uxTopCategoryMenuColumnText.Text
= DataAccessContext.Configurations.GetValue( "NumberOfSubCategoryMenuColumn", CurrentStore );
uxTopCategoryMenuItemText.Text
= DataAccessContext.Configurations.GetValue( "NumberOfSubCategoryMenuItem", CurrentStore );
uxNumberOfManufacturer.Text
= DataAccessContext.Configurations.GetValue( "ManufacturerItemsPerPage", CurrentStore );
uxRestrictAccessToShopDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "RestrictAccessToShop", CurrentStore );
uxPriceRequireLoginDrop.SelectedValue
= DataAccessContext.Configurations.GetValue( "PriceRequireLogin", CurrentStore );
uxRmaDrop.SelectedValue = DataAccessContext.Configurations.GetBoolValue( "EnableRMA", CurrentStore ).ToString();
uxSSLDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "EnableSSL", CurrentStore );
uxAddToCartDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "EnableAddToCartNotification", CurrentStore );
uxQuickViewDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "EnableQuickView", CurrentStore );
uxSaleTaxExemptDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "SaleTaxExempt", CurrentStore );
uxMobileViewDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "MobileView", CurrentStore );
uxManufacturerMenuTypeDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "ManufacturerMenuType", CurrentStore );
uxAdvancedSearchModeDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "AdvancedSearchMode", CurrentStore );
uxReviewPerCultureDrop.SelectedValue = DataAccessContext.Configurations.GetBoolValue( "EnableReviewPerCulture", CurrentStore ).ToString();
uxCheckoutModeDrop.SelectedValue = DataAccessContext.Configurations.GetValue( "CheckoutMode", CurrentStore );
if (!KeyUtilities.IsMultistoreLicense())
{
uxRootCategorySettingPanel.Visible = false;
uxRootDepartmentSettiongPanel.Visible = false;
}
uxWidgetAddThisConfig.PopulateControls( CurrentStore );
uxWidgetLivePersonConfig.PopulateControls( CurrentStore );
uxGoogleAnalyticsConfig.PopulateControls( CurrentStore );
}
public void Update()
{
uxSiteName.Update();
uxLogoImage.Update();
uxDefaultwebsiteLanguage.Update();
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["StoreDefaultCountry"],
uxStoreDefaultCountryDropDown.CurrentSelected,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["SearchMode"],
uxSearchModeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["BundlePromotionShow"],
uxBundlePromotionShowText.Text.Trim(),
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RandomProductShow"],
uxRandomNumberText.Text.Trim(),
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ProductBestSellingShow"],
uxNumberBestSelling.Text.Trim(),
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RootCategory"],
uxRootCategoryDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RootDepartment"],
uxRootDepartmentDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryMenuType"],
uxCategoryMenuTypeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentMenuType"],
uxDepartmentMenuTypeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryMenuLevel"],
uxCategoryMenuLevelText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentMenuLevel"],
uxDepartmentMenuLevelText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryDynamicDropDownDisplay"],
uxCategoryDynamicDropDownDisplayDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentDynamicDropDownDisplay"],
uxDepartmentDynamicDropDownDisplayDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ManufacturerDynamicDropDownDisplay"],
uxManufacturerDynamicDropDownDisplayDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["EnableRMA"],
uxRmaDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryDynamicDropDownLevel"],
uxCategoryDynamicDropDownLevelText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentDynamicDropDownLevel"],
uxDepartmentDynamicDropDownLevelText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryShowProductList"],
uxCategoryShowProductListDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentShowProductList"],
uxDepartmentShowProductListDrop.SelectedValue,
CurrentStore );
uxThemeSelect.Update( CurrentStore );
uxMobileThemeSelect.Update( CurrentStore );
uxCategorySelect.Update( CurrentStore );
uxDepartmentSelect.Update( CurrentStore );
uxProductListSelect.Update( CurrentStore );
uxProductDetailsSelect.Update( CurrentStore );
//uxDefaultMobileThemeSelect.Update( CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["NumberOfCategoryColumn"],
uxNumberOfCategoryColumnText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["NumberOfDepartmentColumn"],
uxNumberOfDepartmentColumnText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["BundlePromotionColumn"],
uxBundlePromotionColumnText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["NumberOfProductColumn"],
uxNumberOfProductColumnText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CategoryItemsPerPage"],
uxNumberOfCategory.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["DepartmentItemsPerPage"],
uxNumberOfDepartment.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["BundlePromotionDisplay"],
uxBundlePromotionDisplayText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["NumberOfSubCategoryMenuColumn"],
uxTopCategoryMenuColumnText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["NumberOfSubCategoryMenuItem"],
uxTopCategoryMenuItemText.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ProductItemsPerPage"],
uxNumberOfProduct.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RecentlyViewedProductShow"],
uxNumberRecentlyViewed.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CompareProductShow"],
uxNumberCompareProduct.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["EnableSSL"],
uxSSLDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["EnableAddToCartNotification"],
uxAddToCartDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["EnableQuickView"],
uxQuickViewDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["SaleTaxExempt"],
uxSaleTaxExemptDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["MobileView"],
uxMobileViewDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ManufacturerMenuType"],
uxManufacturerMenuTypeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["ManufacturerItemsPerPage"],
uxNumberOfManufacturer.Text,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["AdvancedSearchMode"],
uxAdvancedSearchModeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["EnableReviewPerCulture"],
uxReviewPerCultureDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["CheckoutMode"],
uxCheckoutModeDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["RestrictAccessToShop"],
uxRestrictAccessToShopDrop.SelectedValue,
CurrentStore );
DataAccessContext.ConfigurationRepository.UpdateValue(
DataAccessContext.Configurations["PriceRequireLogin"],
uxPriceRequireLoginDrop.SelectedValue,
CurrentStore );
uxWidgetAddThisConfig.Update( CurrentStore );
uxWidgetLivePersonConfig.Update( CurrentStore );
uxGoogleAnalyticsConfig.Update( CurrentStore );
PopulateControls();
}
public string StoreID
{
get
{
if (KeyUtilities.IsMultistoreLicense())
{
return MainContext.QueryString["StoreID"];
}
else
{
return Store.RegularStoreID;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WebApiCors2.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Text;
using Microsoft.Win32;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics.CodeAnalysis;
namespace System.Diagnostics
{
internal static class SharedUtils
{
internal const int UnknownEnvironment = 0;
internal const int W2kEnvironment = 1;
internal const int NtEnvironment = 2;
internal const int NonNtEnvironment = 3;
public const int WAIT_OBJECT_0 = 0x00000000;
public const int WAIT_ABANDONED = 0x00000080;
private static object s_InternalSyncObject;
private static object InternalSyncObject
{
get
{
if (s_InternalSyncObject == null)
{
object o = new object();
Interlocked.CompareExchange(ref s_InternalSyncObject, o, null);
}
return s_InternalSyncObject;
}
}
internal static Win32Exception CreateSafeWin32Exception()
{
return CreateSafeWin32Exception(0);
}
internal static Win32Exception CreateSafeWin32Exception(int error)
{
Win32Exception newException = null;
try
{
if (error == 0)
newException = new Win32Exception();
else
newException = new Win32Exception(error);
}
finally
{
}
return newException;
}
internal static void EnterMutex(string name, ref Mutex mutex)
{
string mutexName = "Global\\" + name;
EnterMutexWithoutGlobal(mutexName, ref mutex);
}
internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
{
bool createdNew;
Mutex tmpMutex = new Mutex(false, mutexName, out createdNew);
SafeWaitForMutex(tmpMutex, ref mutex);
}
// We need to atomically attempt to acquire the mutex and record whether we took it (because we require thread affinity
// while the mutex is held and the two states must be kept in lock step). We can get atomicity with a CER, but we don't want
// to hold a CER over a call to WaitOne (this could cause deadlocks). The final solution is to provide a new API out of
// mscorlib that performs the wait and lets us know if it succeeded. But at this late stage we don't want to expose a new
// API out of mscorlib, so we'll build our own solution.
// We'll P/Invoke out to the WaitForSingleObject inside a CER, but use a timeout to ensure we can't block a thread abort for
// an unlimited time (we do this in an infinite loop so the semantic of acquiring the mutex is unchanged, the timeout is
// just to allow us to poll for abort). A limitation of CERs in Whidbey (and part of the problem that put us in this
// position in the first place) is that a CER root in a method will cause the entire method to delay thread aborts. So we
// need to carefully partition the real CER part of out logic in a sub-method (and ensure the jit doesn't inline on us).
private static bool SafeWaitForMutex(Mutex mutexIn, ref Mutex mutexOut)
{
Debug.Assert(mutexOut == null, "You must pass in a null ref Mutex");
// Wait as long as necessary for the mutex.
while (true)
{
// Attempt to acquire the mutex but timeout quickly if we can't.
if (!SafeWaitForMutexOnce(mutexIn, ref mutexOut))
return false;
if (mutexOut != null)
return true;
// We come out here to the outer method every so often so we're not in a CER and a thread abort can interrupt us.
// But the abort logic itself is poll based (in the this case) so we really need to check for a pending abort
// explicitly else the two timing windows will virtually never line up and we'll still end up stalling the abort
// attempt. Thread.Sleep checks for pending abort for us.
Thread.Sleep(0);
}
}
// The portion of SafeWaitForMutex that runs under a CER and thus must not block for a arbitrary period of time.
// This method must not be inlined (to stop the CER accidently spilling into the calling method).
[MethodImplAttribute(MethodImplOptions.NoInlining)]
private static bool SafeWaitForMutexOnce(Mutex mutexIn, ref Mutex mutexOut)
{
bool ret;
try
{ }
finally
{
// Wait for the mutex for half a second (long enough to gain the mutex in most scenarios and short enough to avoid
// impacting a thread abort for too long).
// Holding a mutex requires us to keep thread affinity and announce ourselves as a critical region.
Thread.BeginCriticalRegion();
Thread.BeginThreadAffinity();
int result = Interop.Kernel32.WaitForSingleObject(mutexIn.SafeWaitHandle, 500);
switch (result)
{
case WAIT_OBJECT_0:
case WAIT_ABANDONED:
// Mutex was obtained, atomically record that fact.
mutexOut = mutexIn;
ret = true;
break;
case Interop.Advapi32.WaitOptions.WAIT_TIMEOUT:
// Couldn't get mutex yet, simply return and we'll try again later.
ret = true;
break;
default:
// Some sort of failure return immediately all the way to the caller of SafeWaitForMutex.
ret = false;
break;
}
// If we're not leaving with the Mutex we don't require thread affinity and we're not a critical region any more.
if (mutexOut == null)
{
Thread.EndThreadAffinity();
Thread.EndCriticalRegion();
}
}
return ret;
}
// What if an app is locked back? Why would we use this?
internal static string GetLatestBuildDllDirectory(string machineName)
{
string dllDir = "";
RegistryKey baseKey = null;
RegistryKey complusReg = null;
try
{
if (machineName == ".")
baseKey = Registry.LocalMachine;
else
baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName);
if (baseKey == null)
throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, "HKEY_LOCAL_MACHINE", machineName));
complusReg = baseKey.OpenSubKey("SOFTWARE\\Microsoft\\.NETFramework");
if (complusReg != null)
{
string installRoot = (string)complusReg.GetValue("InstallRoot");
if (installRoot != null && installRoot != string.Empty)
{
// the "policy" subkey contains a v{major}.{minor} subkey for each version installed. There are also
// some extra subkeys like "standards" and "upgrades" we want to ignore.
// first we figure out what version we are...
string versionPrefix = "v" + Environment.Version.Major + "." + Environment.Version.Minor;
RegistryKey policyKey = complusReg.OpenSubKey("policy");
// This is the full version string of the install on the remote machine we want to use (for example "v2.0.50727")
string version = null;
if (policyKey != null)
{
try
{
// First check to see if there is a version of the runtime with the same minor and major number:
RegistryKey bestKey = policyKey.OpenSubKey(versionPrefix);
if (bestKey != null)
{
try
{
version = versionPrefix + "." + GetLargestBuildNumberFromKey(bestKey);
}
finally
{
bestKey.Close();
}
}
else
{
// There isn't an exact match for our version, so we will look for the largest version
// installed.
string[] majorVersions = policyKey.GetSubKeyNames();
int[] largestVersion = new int[] { -1, -1, -1 };
for (int i = 0; i < majorVersions.Length; i++)
{
string majorVersion = majorVersions[i];
// If this looks like a key of the form v{something}.{something}, we should see if it's a usable build.
if (majorVersion.Length > 1 && majorVersion[0] == 'v' && majorVersion.Contains(".")) // string.Contains(char) is .NetCore2.1+ specific
{
int[] currentVersion = new int[] { -1, -1, -1 };
string[] splitVersion = majorVersion.Substring(1).Split('.');
if (splitVersion.Length != 2)
{
continue;
}
if (!int.TryParse(splitVersion[0], out currentVersion[0]) || !int.TryParse(splitVersion[1], out currentVersion[1]))
{
continue;
}
RegistryKey k = policyKey.OpenSubKey(majorVersion);
if (k == null)
{
// We may be able to use another subkey
continue;
}
try
{
currentVersion[2] = GetLargestBuildNumberFromKey(k);
if (currentVersion[0] > largestVersion[0]
|| ((currentVersion[0] == largestVersion[0]) && (currentVersion[1] > largestVersion[1])))
{
largestVersion = currentVersion;
}
}
finally
{
k.Close();
}
}
}
version = "v" + largestVersion[0] + "." + largestVersion[1] + "." + largestVersion[2];
}
}
finally
{
policyKey.Close();
}
if (version != null && version != string.Empty)
{
StringBuilder installBuilder = new StringBuilder();
installBuilder.Append(installRoot);
if (!installRoot.EndsWith("\\", StringComparison.Ordinal))
installBuilder.Append("\\");
installBuilder.Append(version);
dllDir = installBuilder.ToString();
}
}
}
}
}
catch
{
// ignore
}
finally
{
if (complusReg != null)
complusReg.Close();
if (baseKey != null)
baseKey.Close();
}
return dllDir;
}
private static int GetLargestBuildNumberFromKey(RegistryKey rootKey)
{
int largestBuild = -1;
string[] minorVersions = rootKey.GetValueNames();
for (int i = 0; i < minorVersions.Length; i++)
{
int o;
if (int.TryParse(minorVersions[i], out o))
{
largestBuild = (largestBuild > o) ? largestBuild : o;
}
}
return largestBuild;
}
private static string GetLocalBuildDirectory()
{
return RuntimeEnvironment.GetRuntimeDirectory();
}
}
}
| |
/**************************************
* FILE: EntityExtension.cs
* DATE: 05.01.2010 10:17:01
* AUTHOR: Raphael B. Estrada
* AUTHOR URL: http://www.galaktor.net
* AUTHOR E-MAIL: galaktor@gmx.de
*
* The MIT License
*
* Copyright (c) 2010 Raphael B. Estrada
* Author URL: http://www.galaktor.net
* Author E-Mail: galaktor@gmx.de
*
* 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 NGin.Core.Logging;
using NGin.Core.Systems;
namespace NGin.Core.Scene
{
public class EntityExtension : IEntityExtension
{
#region Fields
#region Private Fields
public bool IsDisposing
{
get;
private set;
}
~EntityExtension()
{
this.Dispose(false);
}
public void Dispose()
{
this.Dispose(true);
}
private void Dispose(bool disposing)
{
this.IsDisposing = true;
if (disposing)
{
this.DisposeManaged();
}
this.DisposeUnmanaged();
}
protected virtual void DisposeUnmanaged()
{ }
protected virtual void DisposeManaged()
{
if ( this.actionRequestBuffer != null )
{
lock ( this.actionRequestBufferLock )
{
this.actionRequestBuffer.Clear();
this.actionRequestBuffer = null;
}
}
if ( this.actionRequestTarget != null )
{
lock ( this.actionRequestTargetLock )
{
this.actionRequestTarget = null;
}
}
if ( this.publicData != null )
{
lock ( this.publicDataLock )
{
this.publicData = null;
}
}
if ( this.handledActionKeys != null )
{
lock ( this.handledActionKeysLock )
{
this.handledActionKeys.Clear();
this.handledActionKeys = null;
}
}
if ( this.System != null )
{
this.System.TaskStarted -= this.System_TaskStarted;
this.System.TaskEnded -= this.System_TaskEnded;
this.System = null;
}
if ( this.LogManager != null )
{
this.LogManager = null;
}
if ( this.Name != null )
{
this.Name = null;
}
}
private object handledActionKeysLock = new object();
private IDictionary<string,EventHandler<ActionRequestEventArgs>> handledActionKeys = new Dictionary<string,EventHandler<ActionRequestEventArgs>>();
protected internal IEnumerable<string> HandledActionKeys
{
get
{
lock ( this.handledActionKeysLock )
{
return this.handledActionKeys.Keys;
}
}
}
protected void AddActionHandler( string actionKey, EventHandler<ActionRequestEventArgs> actionHandler )
{
if ( actionHandler == null )
{
throw new ArgumentNullException( "actionHandler", "The given action handler must not be null." );
}
if ( actionKey == null )
{
throw new ArgumentNullException( "actionKey", "The given action key must not be null." );
}
lock ( this.handledActionKeysLock )
{
if ( this.handledActionKeys.ContainsKey( actionKey ) )
{
this.handledActionKeys[ actionKey ] += actionHandler;
}
else
{
EventHandler<ActionRequestEventArgs> handler = Delegate.Combine( actionHandler ) as EventHandler<ActionRequestEventArgs>;
this.handledActionKeys.Add( actionKey, actionHandler );
}
}
}
protected internal bool TryGetActionHandler( string key, out EventHandler<ActionRequestEventArgs> handler )
{
lock ( this.handledActionKeysLock )
{
return this.handledActionKeys.TryGetValue( key, out handler );
}
}
protected void RemoveActionHandler( string actionKey, EventHandler<ActionRequestEventArgs> actionHandler, bool removeAll )
{
if ( actionHandler == null )
{
throw new ArgumentNullException( "actionHandler", "The given action handler must not be null." );
}
if ( actionKey == null )
{
throw new ArgumentNullException( "actionKey", "The given action key must not be null." );
}
EventHandler<ActionRequestEventArgs> handler = null;
lock ( this.handledActionKeysLock )
{
if ( this.handledActionKeys.TryGetValue( actionKey, out handler ) )
{
if ( removeAll )
{
// will remove all occurances of handler
handler = Delegate.RemoveAll( handler, actionHandler ) as EventHandler<ActionRequestEventArgs>;
}
else
{
// will remove ONLY the last occurance of handler
handler -= actionHandler;
}
if ( handler != null )
{
this.handledActionKeys[ actionKey ] = handler;
}
else
{
this.handledActionKeys.Remove( actionKey );
}
}
else
{
// LOG?
// ignore since the name does not exist
}
}
}
private object actionRequestBufferLock = new object();
private Queue<ActionRequestEventArgs> actionRequestBuffer = new Queue<ActionRequestEventArgs>();
private IEntityExtensionPublicationStorage publicData;
private object publicDataLock = new object();
protected internal ILogManager LogManager { get; set; }
#endregion Private Fields
#endregion Fields
#region Constructors
#region Public Constructors
public EntityExtension( string name, ISystem system, ILogManager logManager )
{
if ( logManager == null )
{
throw new ArgumentNullException( "logManager", "The log manager must not be null." );
}
if ( String.IsNullOrEmpty( name ) )
{
string message = "The given extension name must not be empty or null.";
ArgumentException argEx = new ArgumentException( message, "name" );
logManager.Trace( Namespace.LoggerName, LogLevel.Error, argEx, message );
throw argEx;
}
this.Name = name;
this.System = system;
this.LogManager = logManager;
// register system events
this.System.TaskStarted += new TaskStateChangedDelegate( this.System_TaskStarted );
this.System.TaskEnded += new TaskStateChangedDelegate( this.System_TaskEnded );
}
void System_TaskEnded( ISystem system )
{
if ( this.IsActive )
{
// TODO:
// nothing happens here YET
// could it be wise to have extensions flush their data here?
}
}
void System_TaskStarted( ISystem system )
{
if ( this.IsActive )
{
this.Update();
}
}
#endregion Public Constructors
#endregion Constructors
#region Properties
#region Public Properties
public ISystem System { get; protected internal set; }
public bool IsActive
{
get
{
lock ( this.publicDataLock )
{
return this.PublicData != null;
}
}
}
public string Name
{
get;
protected set;
}
#endregion Public Properties
#region Internal Properties
internal IEntityExtensionPublicationStorage PublicData
{
get
{
lock ( this.publicDataLock )
{
return publicData;
}
}
set
{
lock ( this.publicDataLock )
{
publicData = value;
}
}
}
#endregion Internal Properties
#endregion Properties
#region Methods
#region Public Methods
private object actionRequestTargetLock = new object();
private IActionRequestable actionRequestTarget;
internal IActionRequestable ActionRequestTarget
{
get
{
lock ( this.actionRequestTargetLock )
{
return this.actionRequestTarget;
}
}
private set
{
lock ( this.actionRequestTargetLock )
{
this.actionRequestTarget = value;
}
}
}
public void Attatch( IActionRequestRegistry handlerRegistry, IEntityExtensionPublicationStorage storage, IActionRequestable actionRequestTarget, IUpdateRequester updateRequester )
{
if ( storage == null )
{
throw new ArgumentNullException( "storage", "The given data storage must not be null." );
}
if ( handlerRegistry == null )
{
throw new ArgumentNullException( "handlerRegistry", "The handler registry must not be null." );
}
if ( actionRequestTarget == null )
{
throw new ArgumentNullException( "actionRequestTarget", "The action request target must not be null." );
}
this.PublicData = storage;
this.RegisterActionHandlers( handlerRegistry );
this.ActionRequestTarget = actionRequestTarget;
this.PublicizeEntityProperties( storage );
updateRequester.UpdateRequested += this.PublicizeEntityProperties;
}
public void Detatch( IActionRequestRegistry handlerRegistry, IUpdateRequester updateRequester )
{
this.PublicData = null;
this.UnregisterActionHandlers( handlerRegistry );
this.ActionRequestTarget = null;
updateRequester.UpdateRequested -= this.PublicizeEntityProperties;
}
protected internal void Update()
{
this.ProcessBufferedActionRequests();
this.AqquirePublicEntityProperties( this.PublicData as IEntityExtensionPublicAqquisitionStorage );
this.Process( this.ActionRequestTarget );
//// THIS SHOULD ONLY BE DONE WHEN HEARTBEAT ENDS
//this.PublicizeEntityProperties( this.PublicData );
}
protected virtual void Process( IActionRequestable actionRequestTarget )
{
}
#endregion Public Methods
#region Internal Methods
protected internal void ProcessBufferedActionRequests()
{
lock ( this.actionRequestBufferLock )
{
while (this.actionRequestBuffer.Count > 0)
{
ActionRequestEventArgs args = this.actionRequestBuffer.Dequeue();
EventHandler<ActionRequestEventArgs> handler = null;
if ( this.TryGetActionHandler( args.ActionKey, out handler ) )
{
handler.Invoke( args.RequestingSender, args );
}
else
{
// LOG?
// ERROR: this extension received a a request that it must have registerred before
// but the handler could not be found
throw new InvalidOperationException( "This extension recieved an action request that it cannot handle." );
}
}
}
}
/// <summary>
/// When overridden, an extension will have the chance to get any external entity data
/// before proceeding with it's operations that are based on this data.
/// </summary>
/// <param name="publicDataStorage">The public storage from which data can be aqquired using the methods <see cref="IEntityExtensionPublicAqquisitionStorage.TryGetValue"/> or <see cref="IEntityExtensionPublicAqquisitionStorage.this[ string key ]"/>.</param>
protected virtual void AqquirePublicEntityProperties( IEntityExtensionPublicAqquisitionStorage publicDataStorage )
{
}
/// <summary>
/// When overridden, an extension will have the chance to publicize any data so that it can
/// be accessed by other extensions or from outside of the owning entity.
/// </summary>
/// <param name="publicDataStorage">The public storage into which data can be publicized using <see cref="IEntityExtensionPublicationStorage.Publicize"/></param>
protected virtual void PublicizeEntityProperties( IEntityExtensionPublicationStorage publicDataStorage )
{
}
protected internal void RegisterActionHandlers( IActionRequestRegistry handlerRegistry )
{
lock ( this.handledActionKeysLock )
{
foreach ( string actionKey in this.handledActionKeys.Keys )
{
handlerRegistry.RegisterActionHandler( actionKey, this.BufferActionRequest );
}
}
}
protected internal void UnregisterActionHandlers( IActionRequestRegistry handlerRegistry )
{
lock ( this.handledActionKeysLock )
{
foreach ( string actionKey in this.handledActionKeys.Keys )
{
handlerRegistry.UnregisterActionHandler( actionKey, this.BufferActionRequest, true );
}
}
}
protected internal void BufferActionRequest( object sender, ActionRequestEventArgs e )
{
// exception handling not needed, this has to be fast
// also buffer NULL
// will be checked on dequeue later on
lock ( this.actionRequestBufferLock )
{
this.actionRequestBuffer.Enqueue( e );
}
}
#endregion Internal Methods
#endregion Methods
#region IEquatable<IEntityExtension> Member
public bool Equals( IEntityExtension other )
{
if ( other == null ) return false;
bool nameEqual = ( this.Name == null ) ? other.Name == null : this.Name == other.Name;
bool typeEqual = this.GetType() == other.GetType();
return typeEqual && nameEqual;
}
#endregion
public override bool Equals( object obj )
{
return this.Equals( obj as IEntityExtension );
}
public override int GetHashCode()
{
int nameCode = ( this.Name == null ) ? 0 : this.Name.GetHashCode();
int typeCode = this.GetType().GetHashCode();
return nameCode ^ typeCode;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Filters;
using Xunit;
public class RuleConfigurationTests : NLogTestBase
{
[Fact]
public void NoRulesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
</rules>
</nlog>");
Assert.Equal(0, c.LoggingRules.Count);
}
[Fact]
public void SimpleRuleTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal("*", rule.LoggerNamePattern);
Assert.Equal(FilterResult.Neutral, rule.DefaultFilterResult);
Assert.Equal(4, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
Assert.Equal(1, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.False(rule.Final);
Assert.Equal(0, rule.Filters.Count);
}
[Fact]
public void SingleLevelTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Single(rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MinMaxLevelTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' minLevel='Info' maxLevel='Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Levels.Count);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void NoLevelsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(6, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Debug, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
Assert.Contains(LogLevel.Error, rule.Levels);
Assert.Contains(LogLevel.Fatal, rule.Levels);
}
[Fact]
public void ExplicitLevelsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
</targets>
<rules>
<logger name='*' levels='Trace,Info,Warn' writeTo='d1' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Levels.Count);
Assert.Contains(LogLevel.Trace, rule.Levels);
Assert.Contains(LogLevel.Info, rule.Levels);
Assert.Contains(LogLevel.Warn, rule.Levels);
}
[Fact]
public void MultipleTargetsTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3' />
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(3, rule.Targets.Count);
Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
}
[Fact]
public void MultipleRulesSameTargetTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
<target name='d3' type='Debug' layout='${message}' />
<target name='d4' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1' />
<logger name='*' level='Warn' writeTo='d2' />
<logger name='*' level='Warn' writeTo='d3' />
</rules>
</nlog>");
LogFactory factory = new LogFactory(c);
var loggerConfig = factory.GetConfigurationForLogger("AAA", c);
var targets = loggerConfig.GetTargetsForLevel(LogLevel.Warn);
Assert.Equal("d1", targets.Target.Name);
Assert.Equal("d2", targets.NextInChain.Target.Name);
Assert.Equal("d3", targets.NextInChain.NextInChain.Target.Name);
Assert.Null(targets.NextInChain.NextInChain.NextInChain);
LogManager.Configuration = c;
var logger = LogManager.GetLogger("BBB");
logger.Warn("test1234");
AssertDebugLastMessage("d1", "test1234");
AssertDebugLastMessage("d2", "test1234");
AssertDebugLastMessage("d3", "test1234");
AssertDebugLastMessage("d4", string.Empty);
}
[Fact]
public void ChildRulesTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<logger name='Foo*' writeTo='d4' />
<logger name='Bar*' writeTo='d4' />
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.ChildRules.Count);
Assert.Equal("Foo*", rule.ChildRules[0].LoggerNamePattern);
Assert.Equal("Bar*", rule.ChildRules[1].LoggerNamePattern);
}
[Fact]
public void FiltersTest()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1,d2,d3'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
<when condition=""starts-with(message, 'z')"" action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Assert.Equal(1, c.LoggingRules.Count);
var rule = c.LoggingRules[0];
Assert.Equal(2, rule.Filters.Count);
var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
Assert.NotNull(conditionBasedFilter);
Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
}
[Fact]
public void FiltersTest_ignoreFinal()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='IgnoreFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_logFinal()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='LogFinal' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "x-mass");
AssertDebugLastMessage("d2", "test 1");
}
[Fact]
public void FiltersTest_ignore()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
<target name='d2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters>
<when condition=""starts-with(message, 'x')"" action='Ignore' />
</filters>
</logger>
<logger name='*' level='Warn' writeTo='d2'>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
AssertDebugLastMessage("d2", "x-mass");
}
[Fact]
public void FiltersTest_DefaultAction()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters defaultAction='Ignore'>
<when condition=""starts-with(message, 't')"" action='Log' />
</filters>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
}
[Fact]
public void FiltersTest_FilterDefaultAction()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters filterDefaultAction='Ignore'>
<filter type='when' condition=""starts-with(message, 't')"" action='Log' />
</filters>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "test 1");
logger.Warn("x-mass");
AssertDebugLastMessage("d1", "test 1");
}
[Fact]
public void FiltersTest_DefaultAction_noRules()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='Warn' writeTo='d1'>
<filters defaultAction='Ignore'>
</filters>
</logger>
</rules>
</nlog>");
LogManager.Configuration = c;
var logger = LogManager.GetLogger("logger1");
logger.Warn("test 1");
AssertDebugLastMessage("d1", "");
}
[Fact]
public void LoggingRule_Final_SuppressesOnlyMatchingLevels()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Debug' final='true' />
<logger name='*' minlevel='Debug' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = c;
Logger a = LogManager.GetLogger("a");
Assert.False(a.IsDebugEnabled);
Assert.True(a.IsInfoEnabled);
a.Info("testInfo");
a.Debug("suppressedDebug");
AssertDebugLastMessage("d1", "testInfo");
Logger b = LogManager.GetLogger("b");
b.Debug("testDebug");
AssertDebugLastMessage("d1", "testDebug");
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger()
{
string tempFileName = Path.GetTempFileName();
try
{
var config = XmlLoggingConfiguration.CreateFromXmlString("<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<targets>
<target name='d1' type='Debug' />
<target name='d2' type='Debug' />
<target name='d3' type='Debug' />
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d3' />
</rules>
</nlog>");
var logFactory = new LogFactory();
logFactory.Configuration = config;
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void UnusedTargetsShouldBeLoggedToInternalLogger_PermitWrapped()
{
string tempFileName = Path.GetTempFileName();
try
{
var config = XmlLoggingConfiguration.CreateFromXmlString("<nlog internalLogFile='" + tempFileName + @"' internalLogLevel='Warn'>
<extensions>
<add assembly='NLog.UnitTests'/>
</extensions>
<targets async='true'>
<target name='d1' type='Debug' />
<target name='d2' type='MockWrapper'>
<target name='d3' type='Debug' />
</target>
<target name='d4' type='Debug' />
<target name='d5' type='Debug' />
</targets>
<rules>
<logger name='*' level='Debug' writeTo='d1' />
<logger name='*' level='Debug' writeTo='d1,d2,d4' />
</rules>
</nlog>");
var logFactory = new LogFactory();
logFactory.Configuration = config;
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d2", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d3", Encoding.UTF8);
AssertFileNotContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d4", Encoding.UTF8);
AssertFileContains(tempFileName, "Unused target detected. Add a rule for this target to the configuration. TargetName: d5", Encoding.UTF8);
}
finally
{
NLog.Common.InternalLogger.Reset();
if (File.Exists(tempFileName))
{
File.Delete(tempFileName);
}
}
}
[Fact]
public void LoggingRule_LevelOff_NotSetAsActualLogLevel()
{
LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<target name='l1' type='Debug' layout='${message}' />
<target name='l2' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='a' level='Off' appendTo='l1' />
<logger name='a' minlevel='Debug' appendTo='l2' />
</rules>
</nlog>");
LogManager.Configuration = c;
LogManager.GetLogger("a");
Assert.Equal(2, c.LoggingRules.Count);
Assert.False(c.LoggingRules[0].IsLoggingEnabledForLevel(LogLevel.Off), "Log level Off should always return false.");
// The two functions below should not throw an exception.
c.LoggingRules[0].EnableLoggingForLevel(LogLevel.Debug);
c.LoggingRules[0].DisableLoggingForLevel(LogLevel.Debug);
}
[Theory]
[InlineData("Off")]
[InlineData("")]
[InlineData((string)null)]
[InlineData("Trace")]
[InlineData("Debug")]
[InlineData("Info")]
[InlineData("Warn")]
[InlineData("Error")]
[InlineData(" error")]
[InlineData("Fatal")]
[InlineData("Wrong")]
public void LoggingRule_LevelLayout_ParseLevel(string levelVariable)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (levelVariable != null ? $"<variable name='var_level' value='{levelVariable}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' level='${var:var_level}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
Logger logger = LogManager.GetLogger(nameof(LoggingRule_LevelLayout_ParseLevel));
LogLevel expectedLogLevel = (NLog.Internal.StringHelpers.IsNullOrWhiteSpace(levelVariable) || levelVariable == "Wrong") ? LogLevel.Off : LogLevel.FromString(levelVariable.Trim());
AssertLogLevelEnabled(logger, expectedLogLevel);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_level"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
[Theory]
[MemberData(nameof(LoggingRule_LevelsLayout_ParseLevel_TestCases))]
public void LoggingRule_LevelsLayout_ParseLevel(string levelsVariable, LogLevel[] expectedLevels)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (!string.IsNullOrEmpty(levelsVariable) ? $"<variable name='var_levels' value='{levelsVariable}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' levels='${var:var_levels}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
var logger = LogManager.GetLogger(nameof(LoggingRule_LevelsLayout_ParseLevel));
AssertLogLevelEnabled(logger, expectedLevels);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_levels"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
public static IEnumerable<object[]> LoggingRule_LevelsLayout_ParseLevel_TestCases()
{
yield return new object[] { "Off", new[] { LogLevel.Off } };
yield return new object[] { "Off, Trace", new[] { LogLevel.Off, LogLevel.Trace } };
yield return new object[] { " ", new[] { LogLevel.Off } };
yield return new object[] { " , Debug", new[] { LogLevel.Off, LogLevel.Debug } };
yield return new object[] { "", new[] { LogLevel.Off } };
yield return new object[] { ",Info", new[] { LogLevel.Off, LogLevel.Info } };
yield return new object[] { "Error, Error", new[] { LogLevel.Error, LogLevel.Error } };
yield return new object[] { " error", new[] { LogLevel.Error } };
yield return new object[] { " error, Warn", new[] { LogLevel.Error, LogLevel.Warn } };
yield return new object[] { "Wrong", new[] { LogLevel.Off } };
yield return new object[] { "Wrong, Fatal", new[] { LogLevel.Off, LogLevel.Fatal } };
}
[Theory]
[MemberData(nameof(LoggingRule_MinMaxLayout_ParseLevel_TestCases2))]
public void LoggingRule_MinMaxLayout_ParseLevel(string minLevel, string maxLevel, LogLevel[] expectedLevels)
{
var config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>"
+ (!string.IsNullOrEmpty(minLevel) ? $"<variable name='var_minlevel' value='{minLevel}'/>" : "")
+ (!string.IsNullOrEmpty(maxLevel) ? $"<variable name='var_maxlevel' value='{maxLevel}'/>" : "") +
@"<targets>
<target name='d1' type='Debug' layout='${message}' />
</targets>
<rules>
<logger name='*' minlevel='${var:var_minlevel}' maxlevel='${var:var_maxlevel}' writeTo='d1' />
</rules>
</nlog>");
LogManager.Configuration = config;
var logger = LogManager.GetLogger(nameof(LoggingRule_MinMaxLayout_ParseLevel));
AssertLogLevelEnabled(logger, expectedLevels);
// Verify that runtime override also works
LogManager.Configuration.Variables["var_minlevel"] = LogLevel.Fatal.ToString();
LogManager.Configuration.Variables["var_maxlevel"] = LogLevel.Fatal.ToString();
LogManager.ReconfigExistingLoggers();
AssertLogLevelEnabled(logger, LogLevel.Fatal);
}
public static IEnumerable<object[]> LoggingRule_MinMaxLayout_ParseLevel_TestCases2()
{
yield return new object[] { "Off", "", new LogLevel[] { } };
yield return new object[] { "Off", "Fatal", new LogLevel[] { } };
yield return new object[] { "Error", "Debug", new LogLevel[] { } };
yield return new object[] { " ", "", new LogLevel[] { } };
yield return new object[] { " ", "Fatal", new LogLevel[] { } };
yield return new object[] { "", "", new LogLevel[] { } };
yield return new object[] { "", "Off", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "", "Fatal", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "", "Debug", new[] { LogLevel.Trace, LogLevel.Debug } };
yield return new object[] { "", "Trace", new[] { LogLevel.Trace } };
yield return new object[] { "", " error", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error } };
yield return new object[] { "", "Wrong", new LogLevel[] { } };
yield return new object[] { "Wrong", "", new LogLevel[] { } };
yield return new object[] { "Wrong", "Fatal", new LogLevel[] { } };
yield return new object[] { " error", "Debug", new LogLevel[] { } };
yield return new object[] { " error", "Fatal", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { " error", "", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Error", "", new[] { LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Fatal", "", new[] { LogLevel.Fatal } };
yield return new object[] { "Off", "", new LogLevel[] { } };
yield return new object[] { "Trace", " ", new LogLevel[] { } };
yield return new object[] { "Trace", "", new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal } };
yield return new object[] { "Trace", "Debug", new[] { LogLevel.Trace, LogLevel.Debug } };
yield return new object[] { "Trace", "Trace", new[] { LogLevel.Trace, LogLevel.Trace } };
}
private static void AssertLogLevelEnabled(ILoggerBase logger, LogLevel expectedLogLevel)
{
AssertLogLevelEnabled(logger, new[] {expectedLogLevel });
}
private static void AssertLogLevelEnabled(ILoggerBase logger, LogLevel[] expectedLogLevels)
{
for (int i = LogLevel.MinLevel.Ordinal; i <= LogLevel.MaxLevel.Ordinal; ++i)
{
var logLevel = LogLevel.FromOrdinal(i);
if (expectedLogLevels.Contains(logLevel))
Assert.True(logger.IsEnabled(logLevel),$"{logLevel} expected as true");
else
Assert.False(logger.IsEnabled(logLevel),$"{logLevel} expected as false");
}
}
}
}
| |
using NUnit.Framework;
using DevExpress.Mvvm.Tests;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using DevExpress.Mvvm.Native;
using DevExpress.Mvvm.UI.Interactivity;
using DevExpress.Mvvm.POCO;
using DevExpress.Mvvm.UI.Native;
namespace DevExpress.Mvvm.UI.Tests {
[TestFixture]
public class IWindowSurrogateTests {
[Test]
public void WindowProxyTest() {
Window w = new Window();
var ws1 = WindowProxy.GetWindowSurrogate(w);
var ws2 = WindowProxy.GetWindowSurrogate(w);
Assert.AreSame(ws1, ws2);
}
}
[TestFixture]
public class WindowedDocumentUIServiceTests : BaseWpfFixture {
public class View1 : FrameworkElement { }
public class View2 : FrameworkElement { }
public class EmptyView : FrameworkElement { }
protected class TestStyleSelector : StyleSelector {
public Style Style { get; set; }
public override Style SelectStyle(object item, DependencyObject container) { return Style; }
}
protected class ViewModelWithNullTitle : IDocumentContent {
public IDocumentOwner DocumentOwner { get; set; }
void IDocumentContent.OnClose(CancelEventArgs e) { }
object IDocumentContent.Title { get { return null; } }
void IDocumentContent.OnDestroy() { }
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
try {
WindowedDocumentUIService service = Interaction.GetBehaviors(Window).OfType<WindowedDocumentUIService>().FirstOrDefault();
if (service != null) {
while (service.Documents.Any()) {
service.Documents.First().DestroyOnClose = true;
service.Documents.First().Close(true);
}
}
Interaction.GetBehaviors(Window).Clear();
} catch { }
ViewLocator.Default = null;
base.TearDownCore();
}
[Test]
public void WindowStyle() {
EnqueueShowWindow();
Window.Show();
IDocument document = null;
DispatcherHelper.DoEvents();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(FrameworkElement.TagProperty, "Style Tag"));
service.WindowStyle = windowStyle;
document = service.CreateDocument("EmptyView", new object());
DispatcherHelper.DoEvents();
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Tag", windowDocument.Window.RealWindow.Tag);
}
public class UITestViewModel {
public virtual string Title { get; set; }
public virtual int Parameter { get; set; }
}
[Test]
public void ActivateWhenDocumentShow() {
Window.Show();
IDocument document = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
DispatcherHelper.DoEvents();
document = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document.Show();
DispatcherHelper.DoEvents();
Assert.AreEqual(iService.ActiveDocument, document);
Assert.IsNotNull(document.Content);
Assert.AreEqual(document.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
Assert.AreEqual(document.Content, ((WindowedDocumentUIService.WindowDocument)document).Window.RealWindow.DataContext);
document.Close();
}
[Test]
public void UnActiveDocumentClose() {
Window.Show();
DispatcherHelper.DoEvents();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
Assert.AreEqual(1, counter);
document2.Show();
DispatcherHelper.DoEvents();
Assert.AreEqual(iService.ActiveDocument, document2);
Assert.IsNotNull(document2.Content);
Assert.AreEqual(document2.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
document1.Close();
DispatcherHelper.DoEvents();
Assert.AreEqual(iService.ActiveDocument, document2);
Assert.IsNotNull(document2.Content);
Assert.AreEqual(document2.Content, ViewHelper.GetViewModelFromView(service.ActiveView));
Assert.AreEqual(3, counter);
document2.Close();
}
[Test]
public void SettingActiveDocument() {
Window.Show();
DispatcherHelper.DoEvents();
IDocument document1 = null;
IDocument document2 = null;
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
iService.ActiveDocumentChanged += (s, e) => counter++;
document1 = iService.CreateDocument("View1",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document2 = iService.CreateDocument("View2",
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document1.Show();
document2.Show();
DispatcherHelper.DoEvents();
Assert.AreEqual(3, counter);
iService.ActiveDocument = document1;
DispatcherHelper.DoEvents();
Assert.AreEqual(iService.ActiveDocument, document1);
Assert.AreEqual(4, counter);
document1.Close();
document2.Close();
}
#if !DXCORE3
[Test, Retry(3)]
public void ActivateDocumentsWhenClosed() {
Window.Show();
DispatcherHelper.DoEvents();
List<IDocument> documents = new List<IDocument>();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
int counter = 0;
service.ActiveDocumentChanged += (s, e) => counter++;
for (int i = 0; i < 4; i++) {
documents.Add(iService.CreateDocument("View" + i,
ViewModelSource.Create(() => new UITestViewModel() { Title = "Title" + i, Parameter = i })));
documents[i].Show();
}
iService.ActiveDocument = documents[1];
DispatcherHelper.DoEvents();
counter = 0;
documents[1].Close();
DispatcherHelper.DoEvents();
Assert.AreEqual(2, counter, "#1");
Assert.AreEqual(iService.ActiveDocument, documents[3]);
iService.ActiveDocument = documents[3];
DispatcherHelper.DoEvents();
counter = 0;
documents[3].Close();
DispatcherHelper.DoEvents();
Assert.AreEqual(iService.ActiveDocument, documents[2]);
Assert.AreEqual(2, counter, "#2");
documents[0].Close();
documents[2].Close();
}
#endif
public class BindingTestClass : DependencyObject {
public static readonly DependencyProperty ActiveDocumentProperty =
DependencyProperty.Register("ActiveDocument", typeof(IDocument), typeof(BindingTestClass), new PropertyMetadata(null));
public IDocument ActiveDocument {
get { return (IDocument)GetValue(ActiveDocumentProperty); }
set { SetValue(ActiveDocumentProperty, value); }
}
static readonly DependencyPropertyKey ReadonlyActiveDocumentPropertyKey
= DependencyProperty.RegisterReadOnly("ReadonlyActiveDocument", typeof(IDocument), typeof(BindingTestClass), new PropertyMetadata(null));
public static readonly DependencyProperty ReadonlyActiveDocumentProperty = ReadonlyActiveDocumentPropertyKey.DependencyProperty;
public IDocument ReadonlyActiveDocument {
get { return (IDocument)GetValue(ReadonlyActiveDocumentProperty); }
private set { SetValue(ReadonlyActiveDocumentPropertyKey, value); }
}
}
[Test]
public void TwoWayBinding() {
Window.Show();
DispatcherHelper.DoEvents();
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
IDocument document1 = null;
IDocument document2 = null;
BindingOperations.SetBinding(service, WindowedDocumentUIService.ActiveDocumentProperty,
new Binding() { Path = new PropertyPath(BindingTestClass.ActiveDocumentProperty), Source = testClass, Mode = BindingMode.Default });
document1 = iService.CreateDocument("View1", ViewModelSource.Create(() => new UITestViewModel() { Title = "Title1", Parameter = 1 }));
document1.Show();
DispatcherHelper.DoEvents();
document2 = iService.CreateDocument("View2", ViewModelSource.Create(() => new UITestViewModel() { Title = "Title2", Parameter = 2 }));
document2.Show();
DispatcherHelper.DoEvents();
DispatcherHelper.DoEvents();
Assert.AreSame(document2, service.ActiveDocument);
Assert.AreSame(document2, testClass.ActiveDocument);
testClass.ActiveDocument = document1;
DispatcherHelper.DoEvents();
Assert.AreSame(document1, service.ActiveDocument);
DispatcherHelper.DoEvents();
}
class TestDocumentContent : IDocumentContent {
public Action onClose = null;
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) {
onClose();
}
public void OnDestroy() {
}
public object Title {
get { return ""; }
}
}
[Test]
public void ClosingDocumentOnWindowClosingShouldntThrow() {
Window.Show();
DispatcherHelper.DoEvents();
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
IDocument document = null;
WindowedDocumentUIService.WindowDocument typedDocument = null;
var content = new TestDocumentContent();
document = iService.CreateDocument("View1", content);
typedDocument = (WindowedDocumentUIService.WindowDocument)document;
document.Show();
DispatcherHelper.DoEvents();
Window window = typedDocument.Window.RealWindow;
content.onClose = () => document.Close();
window.Close();
DispatcherHelper.DoEvents();
}
[Test]
public void TwoWayBindingReadonlyProperty() {
BindingTestClass testClass = new BindingTestClass();
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
IDocumentManagerService iService = service;
Assert.Throws<InvalidOperationException>(() => {
BindingOperations.SetBinding(service, WindowedDocumentUIService.ActiveDocumentProperty,
new Binding() { Path = new PropertyPath(BindingTestClass.ReadonlyActiveDocumentProperty), Source = testClass, Mode = BindingMode.Default });
});
}
[Test]
public void WindowStyleSelector() {
WindowedDocumentUIService service = CreateService();
Interaction.GetBehaviors(Window).Add(service);
service.WindowType = typeof(Window);
Style windowStyle = new Style(typeof(Window));
windowStyle.Setters.Add(new Setter(System.Windows.Window.TagProperty, "Style Selector Tag"));
service.WindowStyleSelector = new TestStyleSelector() { Style = windowStyle };
IDocument document = service.CreateDocument("EmptyView", new object());
var windowDocument = (WindowedDocumentUIService.WindowDocument)document;
Assert.AreEqual("Style Selector Tag", windowDocument.Window.RealWindow.Tag);
}
protected virtual WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService() { WindowType = typeof(Window) };
}
}
[TestFixture]
public class WindowedDocumentUIServiceIDocumentContentCloseTests : BaseWpfFixture {
public class EmptyView : FrameworkElement { }
class TestDocumentContent : IDocumentContent {
Func<bool> close;
Action onDestroy;
public TestDocumentContent(Func<bool> close, Action onDestroy = null) {
this.close = close;
this.onDestroy = onDestroy;
}
public IDocumentOwner DocumentOwner { get; set; }
public void OnClose(CancelEventArgs e) { e.Cancel = !close(); }
public object Title { get { return null; } }
void IDocumentContent.OnDestroy() {
if(onDestroy != null)
onDestroy();
}
}
protected override void SetUpCore() {
base.SetUpCore();
ViewLocator.Default = new TestViewLocator(this);
}
protected override void TearDownCore() {
try {
WindowedDocumentUIService service = Interaction.GetBehaviors(Window).OfType<WindowedDocumentUIService>().FirstOrDefault();
if (service != null) {
while (service.Documents.Any()) {
service.Documents.First().DestroyOnClose = true;
service.Documents.First().Close(true);
}
}
Interaction.GetBehaviors(Window).Clear();
} catch { }
ViewLocator.Default = null;
base.TearDownCore();
}
protected virtual WindowedDocumentUIService CreateService() {
return new WindowedDocumentUIService() { WindowType = typeof(Window) };
}
void DoCloseTest(bool allowClose, bool destroyOnClose, bool destroyed, Action<IDocument> closeMethod) {
DoCloseTest((bool?)allowClose, destroyOnClose, destroyed, (d, b) => closeMethod(d));
}
void DoCloseTest(bool? allowClose, bool destroyOnClose, bool destroyed, Action<IDocument, bool> closeMethod) {
Window.Show();
DispatcherHelper.DoEvents();
IDocumentManagerService service = null;
bool closeChecked = false;
bool destroyCalled = false;
IDocument document = null;
WindowedDocumentUIService windowedDocumentUIService = CreateService();
Interaction.GetBehaviors(Window).Add(windowedDocumentUIService);
service = windowedDocumentUIService;
TestDocumentContent viewModel = new TestDocumentContent(() => {
closeChecked = true;
return allowClose != null && allowClose.Value;
}, () => {
destroyCalled = true;
});
document = service.CreateDocument("EmptyView", viewModel);
document.Show();
DispatcherHelper.DoEvents();
document.DestroyOnClose = destroyOnClose;
closeMethod(document, allowClose == null);
Assert.AreEqual(allowClose != null, closeChecked);
Assert.AreEqual(destroyed, destroyCalled);
Assert.AreEqual(!destroyed, service.Documents.Contains(document));
}
void CloseDocument(IDocument document, bool force) {
document.Close(force);
}
void CloseDocumentWithDocumentOwner(IDocument document, bool force) {
IDocumentContent documentContent = (IDocumentContent)document.Content;
documentContent.DocumentOwner.Close(documentContent, force);
}
void CloseDocumentWithClosingWindow(IDocument document) {
Window window = ((WindowedDocumentUIService.WindowDocument)document).Window.RealWindow;
window.Close();
}
[Test]
public void IDocumentViewModelCloseTest1() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest2() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test]
public void IDocumentViewModelCloseTest12() {
DoCloseTest(allowClose: false, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test]
public void IDocumentViewModelCloseTest3() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest4() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test]
public void IDocumentViewModelCloseTest14() {
DoCloseTest(allowClose: false, destroyOnClose: true, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test]
public void IDocumentViewModelCloseTest5() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest6() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test]
public void IDocumentViewModelCloseTest16() {
DoCloseTest(allowClose: true, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithClosingWindow);
}
[Test]
public void IDocumentViewModelCloseTest7() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest8() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test]
public void IDocumentViewModelCloseTest18() {
DoCloseTest(allowClose: true, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithClosingWindow);
}
[Test]
public void IDocumentViewModelCloseTest9() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest10() {
DoCloseTest(allowClose: null, destroyOnClose: false, destroyed: false, closeMethod: CloseDocumentWithDocumentOwner);
}
[Test]
public void IDocumentViewModelCloseTest11() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocument);
}
[Test]
public void IDocumentViewModelCloseTest13() {
DoCloseTest(allowClose: null, destroyOnClose: true, destroyed: true, closeMethod: CloseDocumentWithDocumentOwner);
}
}
public class TestViewLocator : IViewLocator {
Dictionary<string, Type> types;
IViewLocator innerViewLocator;
public TestViewLocator(object ownerTypeInstance, IViewLocator innerViewLocator = null) : this(ownerTypeInstance.GetType(), innerViewLocator) { }
public TestViewLocator(Type ownerType, IViewLocator innerViewLocator = null) {
this.innerViewLocator = innerViewLocator;
types = GetBaseTypes(ownerType).SelectMany(x => x.GetNestedTypes(BindingFlags.Public)).ToDictionary(t => t.Name, t => t);
}
object IViewLocator.ResolveView(string name) {
Type type;
return types.TryGetValue(name, out type) ? Activator.CreateInstance(type) : innerViewLocator.With(i => i.ResolveView(name));
}
Type IViewLocator.ResolveViewType(string name) {
throw new NotImplementedException();
}
IEnumerable<Type> GetBaseTypes(Type type) {
for(var baseType = type; baseType != null; baseType = baseType.BaseType)
yield return baseType;
}
string IViewLocator.GetViewTypeName(Type type) {
throw new NotImplementedException();
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
#region license
/*
DirectShowLib - Provide access to DirectShow interfaces via .NET
Copyright (C) 2006
http://sourceforge.net/projects/directshownet/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endregion
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace DirectShowLib.SBE
{
#region Declarations
/// <summary>
/// From unnamed structure
/// </summary>
public enum RecordingType
{
Content = 0, // no post-recording or overlapped
Reference // allows post-recording & overlapped
}
/// <summary>
/// From STREAMBUFFER_ATTR_DATATYPE
/// </summary>
public enum StreamBufferAttrDataType
{
DWord = 0,
String = 1,
Binary = 2,
Bool = 3,
QWord = 4,
Word = 5,
Guid = 6
}
/// <summary>
/// From unnamed structure
/// </summary>
public enum StreamBufferEventCode
{
TimeHole = 0x0326, // STREAMBUFFER_EC_TIMEHOLE
StaleDataRead, // STREAMBUFFER_EC_STALE_DATA_READ
StaleFileDeleted, // STREAMBUFFER_EC_STALE_FILE_DELETED
ContentBecomingStale, // STREAMBUFFER_EC_CONTENT_BECOMING_STALE
WriteFailure, // STREAMBUFFER_EC_WRITE_FAILURE
ReadFailure, // STREAMBUFFER_EC_READ_FAILURE
RateChanged // STREAMBUFFER_EC_RATE_CHANGED
}
/// <summary>
/// From g_wszStreamBufferRecording* static const WCHAR
/// </summary>
sealed public class StreamBufferRecording
{
private StreamBufferRecording()
{
}
////////////////////////////////////////////////////////////////
//
// List of pre-defined attributes
//
public readonly string Duration = "Duration";
public readonly string Bitrate = "Bitrate";
public readonly string Seekable = "Seekable";
public readonly string Stridable = "Stridable";
public readonly string Broadcast = "Broadcast";
public readonly string Protected = "Is_Protected";
public readonly string Trusted = "Is_Trusted";
public readonly string Signature_Name = "Signature_Name";
public readonly string HasAudio = "HasAudio";
public readonly string HasImage = "HasImage";
public readonly string HasScript = "HasScript";
public readonly string HasVideo = "HasVideo";
public readonly string CurrentBitrate = "CurrentBitrate";
public readonly string OptimalBitrate = "OptimalBitrate";
public readonly string HasAttachedImages = "HasAttachedImages";
public readonly string SkipBackward = "Can_Skip_Backward";
public readonly string SkipForward = "Can_Skip_Forward";
public readonly string NumberOfFrames = "NumberOfFrames";
public readonly string FileSize = "FileSize";
public readonly string HasArbitraryDataStream = "HasArbitraryDataStream";
public readonly string HasFileTransferStream = "HasFileTransferStream";
////////////////////////////////////////////////////////////////
//
// The content description object supports 5 basic attributes.
//
public readonly string Title = "Title";
public readonly string Author = "Author";
public readonly string Description = "Description";
public readonly string Rating = "Rating";
public readonly string Copyright = "Copyright";
////////////////////////////////////////////////////////////////
//
// These attributes are used to configure DRM using IWMDRMWriter::SetDRMAttribute.
//
public readonly string Use_DRM = "Use_DRM";
public readonly string DRM_Flags = "DRM_Flags";
public readonly string DRM_Level = "DRM_Level";
////////////////////////////////////////////////////////////////
//
// These are the additional attributes defined in the WM attribute
// namespace that give information about the content.
//
public readonly string AlbumTitle = "WM/AlbumTitle";
public readonly string Track = "WM/Track";
public readonly string PromotionURL = "WM/PromotionURL";
public readonly string AlbumCoverURL = "WM/AlbumCoverURL";
public readonly string Genre = "WM/Genre";
public readonly string Year = "WM/Year";
public readonly string GenreID = "WM/GenreID";
public readonly string MCDI = "WM/MCDI";
public readonly string Composer = "WM/Composer";
public readonly string Lyrics = "WM/Lyrics";
public readonly string TrackNumber = "WM/TrackNumber";
public readonly string ToolName = "WM/ToolName";
public readonly string ToolVersion = "WM/ToolVersion";
public readonly string IsVBR = "IsVBR";
public readonly string AlbumArtist = "WM/AlbumArtist";
////////////////////////////////////////////////////////////////
//
// These optional attributes may be used to give information
// about the branding of the content.
//
public readonly string BannerImageType = "BannerImageType";
public readonly string BannerImageData = "BannerImageData";
public readonly string BannerImageURL = "BannerImageURL";
public readonly string CopyrightURL = "CopyrightURL";
////////////////////////////////////////////////////////////////
//
// Optional attributes, used to give information
// about video stream properties.
//
public readonly string AspectRatioX = "AspectRatioX";
public readonly string AspectRatioY = "AspectRatioY";
////////////////////////////////////////////////////////////////
//
// The NSC file supports the following attributes.
//
public readonly string NSCName = "NSC_Name";
public readonly string NSCAddress = "NSC_Address";
public readonly string NSCPhone = "NSC_Phone";
public readonly string NSCEmail = "NSC_Email";
public readonly string NSCDescription = "NSC_Description";
}
/// <summary>
/// From STREAMBUFFER_ATTRIBUTE
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct StreamBufferAttribute
{
[MarshalAs(UnmanagedType.LPWStr)] public string pszName;
public StreamBufferAttrDataType StreamBufferAttributeType;
public IntPtr pbAttribute; // BYTE *
public short cbLength;
}
/// <summary>
/// From SBE_PIN_DATA
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct SBEPinData
{
public long cDataBytes; // total sample payload bytes
public long cSamplesProcessed; // samples processed
public long cDiscontinuities; // number of discontinuities
public long cSyncPoints; // number of syncpoints
public long cTimestamps; // number of timestamps
}
#endregion
#region Interfaces
[ComImport,
Guid("9ce50f2d-6ba7-40fb-a034-50b1a674ec78"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferInitialize
{
[PreserveSig]
int SetHKEY([In] IntPtr hkeyRoot); // HKEY
[PreserveSig]
int SetSIDs(
[In] int cSIDs,
[In, MarshalAs(UnmanagedType.LPArray)] IntPtr [] ppSID // PSID *
);
}
[ComImport,
Guid("afd1f242-7efd-45ee-ba4e-407a25c9a77a"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink
{
[PreserveSig]
int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
int IsProfileLocked();
}
[ComImport,
Guid("DB94A660-F4FB-4bfa-BCC6-FE159A4EEA93"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink2 : IStreamBufferSink
{
#region IStreamBufferSink Methods
[PreserveSig]
new int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
new int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
new int IsProfileLocked();
#endregion
[PreserveSig]
int UnlockProfile();
}
[ComImport,
Guid("974723f2-887a-4452-9366-2cff3057bc8f"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSink3 : IStreamBufferSink2
{
#region IStreamBufferSink Methods
[PreserveSig]
new int LockProfile([In, MarshalAs(UnmanagedType.LPWStr)] string pszStreamBufferFilename);
[PreserveSig]
new int CreateRecorder(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszFilename,
[In] RecordingType dwRecordType,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object pRecordingIUnknown
);
[PreserveSig]
new int IsProfileLocked();
#endregion
#region IStreamBufferSink2
[PreserveSig]
new int UnlockProfile();
#endregion
[PreserveSig]
int SetAvailableFilter([In, Out] ref long prtMin);
}
[ComImport,
Guid("1c5bd776-6ced-4f44-8164-5eab0e98db12"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferSource
{
[PreserveSig]
int SetStreamSink([In] IStreamBufferSink pIStreamBufferSink);
}
[ComImport,
Guid("ba9b6c99-f3c7-4ff2-92db-cfdd4851bf31"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecordControl
{
[PreserveSig]
int Start([In, Out] ref long prtStart);
[PreserveSig]
int Stop([In] long rtStop);
[PreserveSig]
int GetRecordingStatus(
[Out] out int phResult,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pbStarted,
[Out, MarshalAs(UnmanagedType.Bool)] out bool pbStopped
);
}
[ComImport,
Guid("9E259A9B-8815-42ae-B09F-221970B154FD"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecComp
{
[PreserveSig]
int Initialize(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszTargetFilename,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecProfileRef
);
[PreserveSig]
int Append([In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecording);
[PreserveSig]
int AppendEx(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSBRecording,
[In] long rtStart,
[In] long rtStop
);
[PreserveSig]
int GetCurrentLength([Out] out int pcSeconds);
[PreserveSig]
int Close();
[PreserveSig]
int Cancel();
}
[ComImport,
Guid("16CA4E03-FE69-4705-BD41-5B7DFC0C95F3"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferRecordingAttribute
{
[PreserveSig]
int SetAttribute(
[In] int ulReserved,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAttributeName,
[In] StreamBufferAttrDataType StreamBufferAttributeType,
[In] IntPtr pbAttribute, // BYTE *
[In] short cbAttributeLength
);
[PreserveSig]
int GetAttributeCount(
[In] int ulReserved,
[Out] out short pcAttributes
);
[PreserveSig]
int GetAttributeByName(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAttributeName,
[In] int pulReserved,
[Out] out StreamBufferAttrDataType pStreamBufferAttributeType,
[In, Out] IntPtr pbAttribute, // BYTE *
[In, Out] ref short pcbLength
);
[PreserveSig]
int GetAttributeByIndex(
[In] short wIndex,
[In] int pulReserved,
[Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszAttributeName,
[In, Out] ref short pcchNameLength,
[Out] out StreamBufferAttrDataType pStreamBufferAttributeType,
IntPtr pbAttribute, // BYTE *
[In, Out] ref short pcbLength
);
int EnumAttributes([Out] out IEnumStreamBufferRecordingAttrib ppIEnumStreamBufferAttrib);
}
[ComImport,
Guid("C18A9162-1E82-4142-8C73-5690FA62FE33"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEnumStreamBufferRecordingAttrib
{
[PreserveSig]
int Next(
[In] int cRequest,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex=0)] StreamBufferAttribute[] pStreamBufferAttribute,
[Out] out int pcReceived
);
[PreserveSig]
int Skip([In] int cRecords);
[PreserveSig]
int Reset();
[PreserveSig]
int Clone([Out] out IEnumStreamBufferRecordingAttrib ppIEnumStreamBufferAttrib);
}
[ComImport,
Guid("ce14dfae-4098-4af7-bbf7-d6511f835414"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferConfigure
{
[PreserveSig]
int SetDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszDirectoryName);
[PreserveSig]
int GetDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] out string pszDirectoryName);
[PreserveSig]
int SetBackingFileCount(
[In] int dwMin,
[In] int dwMax
);
[PreserveSig]
int GetBackingFileCount(
[Out] out int dwMin,
[Out] out int dwMax
);
[PreserveSig]
int SetBackingFileDuration([In] int dwSeconds);
[PreserveSig]
int GetBackingFileDuration([Out] out int pdwSeconds);
}
[ComImport,
Guid("53E037BF-3992-4282-AE34-2487B4DAE06B"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferConfigure2 : IStreamBufferConfigure
{
#region IStreamBufferConfigure
[PreserveSig]
new int SetDirectory([In, MarshalAs(UnmanagedType.LPWStr)] string pszDirectoryName);
[PreserveSig]
new int GetDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] out string pszDirectoryName);
[PreserveSig]
new int SetBackingFileCount(
[In] int dwMin,
[In] int dwMax
);
[PreserveSig]
new int GetBackingFileCount(
[Out] out int dwMin,
[Out] out int dwMax
);
[PreserveSig]
new int SetBackingFileDuration([In] int dwSeconds);
[PreserveSig]
new int GetBackingFileDuration([Out] out int pdwSeconds);
#endregion
[PreserveSig]
int SetMultiplexedPacketSize([In] int cbBytesPerPacket);
[PreserveSig]
int GetMultiplexedPacketSize([Out] out int pcbBytesPerPacket);
[PreserveSig]
int SetFFTransitionRates(
[In] int dwMaxFullFrameRate,
[In] int dwMaxNonSkippingRate
);
[PreserveSig]
int GetFFTransitionRates(
[Out] out int pdwMaxFullFrameRate,
[Out] out int pdwMaxNonSkippingRate
);
}
[ComImport,
Guid("f61f5c26-863d-4afa-b0ba-2f81dc978596"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferMediaSeeking : IMediaSeeking
{
#region IMediaSeeking Methods
[PreserveSig]
new int GetCapabilities([Out] out AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int CheckCapabilities([In, Out] ref AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int IsFormatSupported([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int QueryPreferredFormat([Out] out Guid pFormat);
[PreserveSig]
new int GetTimeFormat([Out] out Guid pFormat);
[PreserveSig]
new int IsUsingTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int SetTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int GetDuration([Out] out long pDuration);
[PreserveSig]
new int GetStopPosition([Out] out long pStop);
[PreserveSig]
new int GetCurrentPosition([Out] out long pCurrent);
[PreserveSig]
new int ConvertTimeFormat(
[Out] out long pTarget,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pTargetFormat,
[In] long Source,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pSourceFormat
);
[PreserveSig]
new int SetPositions(
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pCurrent,
[In] AMSeekingSeekingFlags dwCurrentFlags,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pStop,
[In] AMSeekingSeekingFlags dwStopFlags
);
[PreserveSig]
new int GetPositions(
[Out] out long pCurrent,
[Out] out long pStop
);
[PreserveSig]
new int GetAvailable(
[Out] out long pEarliest,
[Out] out long pLatest
);
[PreserveSig]
new int SetRate([In] double dRate);
[PreserveSig]
new int GetRate([Out] out double pdRate);
[PreserveSig]
new int GetPreroll([Out] out long pllPreroll);
#endregion
}
[ComImport,
Guid("3a439ab0-155f-470a-86a6-9ea54afd6eaf"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferMediaSeeking2 : IStreamBufferMediaSeeking
{
#region IMediaSeeking
[PreserveSig]
new int GetCapabilities([Out] out AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int CheckCapabilities([In, Out] ref AMSeekingSeekingCapabilities pCapabilities);
[PreserveSig]
new int IsFormatSupported([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int QueryPreferredFormat([Out] out Guid pFormat);
[PreserveSig]
new int GetTimeFormat([Out] out Guid pFormat);
[PreserveSig]
new int IsUsingTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int SetTimeFormat([In, MarshalAs(UnmanagedType.LPStruct)] Guid pFormat);
[PreserveSig]
new int GetDuration([Out] out long pDuration);
[PreserveSig]
new int GetStopPosition([Out] out long pStop);
[PreserveSig]
new int GetCurrentPosition([Out] out long pCurrent);
[PreserveSig]
new int ConvertTimeFormat(
[Out] out long pTarget,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pTargetFormat,
[In] long Source,
[In, MarshalAs(UnmanagedType.LPStruct)] DsGuid pSourceFormat
);
[PreserveSig]
new int SetPositions(
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pCurrent,
[In] AMSeekingSeekingFlags dwCurrentFlags,
[In, Out, MarshalAs(UnmanagedType.LPStruct)] DsLong pStop,
[In] AMSeekingSeekingFlags dwStopFlags
);
[PreserveSig]
new int GetPositions(
[Out] out long pCurrent,
[Out] out long pStop
);
[PreserveSig]
new int GetAvailable(
[Out] out long pEarliest,
[Out] out long pLatest
);
[PreserveSig]
new int SetRate([In] double dRate);
[PreserveSig]
new int GetRate([Out] out double pdRate);
[PreserveSig]
new int GetPreroll([Out] out long pllPreroll);
#endregion
[PreserveSig]
int SetRateEx(
[In] double dRate,
[In] int dwFramesPerSec
);
}
[ComImport,
Guid("9D2A2563-31AB-402e-9A6B-ADB903489440"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IStreamBufferDataCounters
{
[PreserveSig]
int GetData([Out] out SBEPinData pPinData);
[PreserveSig]
int ResetData();
}
#endregion
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using System;
using Esri.ArcGISRuntime;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using Windows.UI.Popups;
using Windows.UI.Xaml;
namespace ArcGISRuntime.UWP.Samples.ListTransformations
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "List transformations by suitability",
category: "Geometry",
description: "Get a list of suitable transformations for projecting a geometry between two spatial references with different horizontal datums.",
instructions: "Select a transformation from the list to see the result of projecting the point from EPSG:27700 to EPSG:3857 using that transformation. The result is shown as a red cross; you can visually compare the original blue point with the projected red cross.",
tags: new[] { "datum", "geodesy", "projection", "spatial reference", "transformation" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData()]
public partial class ListTransformations : INotifyPropertyChanged
{
// Point whose coordinates will be projected using a selected transform.
private MapPoint _originalPoint;
// Graphic representing the projected point.
private Graphic _projectedPointGraphic;
// GraphicsOverlay to hold the point graphics.
private GraphicsOverlay _pointsOverlay;
// Property to expose the list of datum transformations for binding to the list box.
private IReadOnlyList<DatumTransformationListBoxItem> _datumTransformations;
public IReadOnlyList<DatumTransformationListBoxItem> SuitableTransformationsList
{
get
{
return _datumTransformations;
}
set
{
_datumTransformations = value;
OnPropertyChanged("SuitableTransformationsList");
}
}
// Implement INotifyPropertyChanged to indicate when the list of transformations has been updated.
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public ListTransformations()
{
InitializeComponent();
Initialize();
}
private async void Initialize()
{
// Create the map.
Map myMap = new Map(BasemapStyle.ArcGISImagery);
// Create a point in the Greenwich observatory courtyard in London, UK, the location of the prime meridian.
_originalPoint = new MapPoint(538985.355, 177329.516, SpatialReference.Create(27700));
// Set the initial extent to an extent centered on the point.
Viewpoint initialViewpoint = new Viewpoint(_originalPoint, 5000);
myMap.InitialViewpoint = initialViewpoint;
// Add the map to the map view.
MyMapView.Map = myMap;
// Create a graphics overlay to hold the original and projected points.
_pointsOverlay = new GraphicsOverlay();
MyMapView.GraphicsOverlays.Add(_pointsOverlay);
// Add the point as a graphic with a blue square.
SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Square, Color.Blue, 15);
Graphic originalGraphic = new Graphic(_originalPoint, markerSymbol);
_pointsOverlay.Graphics.Add(originalGraphic);
// Get the path to the projection engine data (if it exists).
string peFolderPath = GetProjectionDataPath();
if (!String.IsNullOrEmpty(peFolderPath))
{
TransformationCatalog.ProjectionEngineDirectory = peFolderPath;
MessagesTextBox.Text = "Using projection data found at '" + peFolderPath + "'";
}
else
{
MessagesTextBox.Text = "Projection engine data not found.";
}
try
{
// Wait for the map to load so that it has a spatial reference.
await myMap.LoadAsync();
// Show the input and output spatial reference.
InSpatialRefTextBox.Text = "In WKID = " + _originalPoint.SpatialReference.Wkid;
OutSpatialRefTextBox.Text = "Out WKID = " + myMap.SpatialReference.Wkid;
// Create a list of transformations to fill the UI list box.
GetSuitableTransformations(_originalPoint.SpatialReference, myMap.SpatialReference, UseExtentCheckBox.IsChecked == true);
}
catch (Exception e)
{
await new MessageDialog(e.ToString(), "Error").ShowAsync();
}
}
// Function to get suitable datum transformations for the specified input and output spatial references.
private void GetSuitableTransformations(SpatialReference inSpatialRef, SpatialReference outSpatialRef, bool considerExtent)
{
// Get suitable transformations. Use the current extent to evaluate suitability, if requested.
IReadOnlyList<DatumTransformation> transformations;
if (considerExtent)
{
Envelope currentExtent = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry).TargetGeometry as Envelope;
transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef, currentExtent);
}
else
{
transformations = TransformationCatalog.GetTransformationsBySuitability(inSpatialRef, outSpatialRef);
}
// Get the default transformation for the specified input and output spatial reference.
DatumTransformation defaultTransform = TransformationCatalog.GetTransformation(inSpatialRef, outSpatialRef);
List<DatumTransformationListBoxItem> transformationItems = new List<DatumTransformationListBoxItem>();
// Wrap the transformations in a class that includes a boolean to indicate if it's the default transformation.
foreach (DatumTransformation transform in transformations)
{
DatumTransformationListBoxItem item = new DatumTransformationListBoxItem(transform)
{
IsDefault = (transform.Name == defaultTransform.Name)
};
transformationItems.Add(item);
}
// Set the transformation list property that the list box binds to.
SuitableTransformationsList = transformationItems;
}
private void TransformationsListBox_Selected(object sender, RoutedEventArgs e)
{
// Get the selected transform from the list box. Return if there isn't a selected item.
DatumTransformationListBoxItem selectedListBoxItem = TransformationsListBox.SelectedItem as DatumTransformationListBoxItem;
if (selectedListBoxItem == null) { return; }
DatumTransformation selectedTransform = selectedListBoxItem.TransformationObject;
try
{
// Project the original point using the selected transform.
MapPoint projectedPoint = (MapPoint)GeometryEngine.Project(_originalPoint, MyMapView.SpatialReference, selectedTransform);
// Update the projected graphic (if it already exists), create it otherwise.
if (_projectedPointGraphic != null)
{
_projectedPointGraphic.Geometry = projectedPoint;
}
else
{
// Create a symbol to represent the projected point (a cross to ensure both markers are visible).
SimpleMarkerSymbol projectedPointMarker = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, Color.Red, 15);
// Create the point graphic and add it to the overlay.
_projectedPointGraphic = new Graphic(projectedPoint, projectedPointMarker);
_pointsOverlay.Graphics.Add(_projectedPointGraphic);
}
MessagesTextBox.Text = "Projected point using transform: " + selectedTransform.Name;
}
catch (ArcGISRuntimeException ex)
{
// Exception if a transformation is missing grid files.
MessagesTextBox.Text = "Error using selected transformation: " + ex.Message;
// Remove the projected point graphic (if it exists).
if (_projectedPointGraphic != null && _pointsOverlay.Graphics.Contains(_projectedPointGraphic))
{
_pointsOverlay.Graphics.Remove(_projectedPointGraphic);
_projectedPointGraphic = null;
}
}
}
private void UseExtentCheckBox_CheckChanged(object sender, RoutedEventArgs e)
{
// Recreate the contents of the datum transformations list box.
GetSuitableTransformations(_originalPoint.SpatialReference, MyMapView.Map.SpatialReference, UseExtentCheckBox.IsChecked == true);
}
private string GetProjectionDataPath()
{
// Return the projection data path; note that this is not valid by default.
//You must manually download the projection engine data and update the path returned here.
return "";
}
}
// A class that wraps a DatumTransformation object and adds a property that indicates if it's the default transformation.
public class DatumTransformationListBoxItem
{
// Datum transformation object.
public DatumTransformation TransformationObject { get; set; }
// Whether or not this transformation is the default (for the specified in/out spatial reference).
public bool IsDefault { get; set; }
// Constructor that takes the DatumTransformation object to wrap.
public DatumTransformationListBoxItem(DatumTransformation transformation)
{
TransformationObject = transformation;
}
}
}
| |
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1)
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Schema
{
internal class JsonSchemaWriter
{
private readonly JsonWriter _writer;
private readonly JsonSchemaResolver _resolver;
public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver)
{
ValidationUtils.ArgumentNotNull(writer, "writer");
_writer = writer;
_resolver = resolver;
}
private void ReferenceOrWriteSchema(JsonSchema schema)
{
if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.ReferencePropertyName);
_writer.WriteValue(schema.Id);
_writer.WriteEndObject();
}
else
{
WriteSchema(schema);
}
}
public void WriteSchema(JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(schema, "schema");
if (!_resolver.LoadedSchemas.Contains(schema))
_resolver.LoadedSchemas.Add(schema);
_writer.WriteStartObject();
WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
if (schema.Type != null)
WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
if (!schema.AllowAdditionalProperties)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
_writer.WriteValue(schema.AllowAdditionalProperties);
}
else
{
if (schema.AdditionalProperties != null)
{
_writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
ReferenceOrWriteSchema(schema.AdditionalProperties);
}
}
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
WriteItems(schema);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
if (schema.Enum != null)
{
_writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
_writer.WriteStartArray();
foreach (JToken token in schema.Enum)
{
token.WriteTo(_writer);
}
_writer.WriteEndArray();
}
if (schema.Default != null)
{
_writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
schema.Default.WriteTo(_writer);
}
if (schema.Options != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionsPropertyName);
_writer.WriteStartArray();
foreach (KeyValuePair<JToken, string> option in schema.Options)
{
_writer.WriteStartObject();
_writer.WritePropertyName(JsonSchemaConstants.OptionValuePropertyName);
option.Key.WriteTo(_writer);
if (option.Value != null)
{
_writer.WritePropertyName(JsonSchemaConstants.OptionLabelPropertyName);
_writer.WriteValue(option.Value);
}
_writer.WriteEndObject();
}
_writer.WriteEndArray();
}
if (schema.Disallow != null)
WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.Value);
if (schema.Extends != null)
{
_writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName);
ReferenceOrWriteSchema(schema.Extends);
}
_writer.WriteEndObject();
}
private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties)
{
if (properties != null)
{
writer.WritePropertyName(propertyName);
writer.WriteStartObject();
foreach (KeyValuePair<string, JsonSchema> property in properties)
{
writer.WritePropertyName(property.Key);
ReferenceOrWriteSchema(property.Value);
}
writer.WriteEndObject();
}
}
private void WriteItems(JsonSchema schema)
{
if (CollectionUtils.IsNullOrEmpty(schema.Items))
return;
_writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);
if (schema.Items.Count == 1)
{
ReferenceOrWriteSchema(schema.Items[0]);
return;
}
_writer.WriteStartArray();
foreach (JsonSchema itemSchema in schema.Items)
{
ReferenceOrWriteSchema(itemSchema);
}
_writer.WriteEndArray();
}
private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type)
{
IList<JsonSchemaType> types;
if (System.Enum.IsDefined(typeof(JsonSchemaType), type))
types = new List<JsonSchemaType> { type };
else
types = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).ToList();
if (types.Count == 0)
return;
writer.WritePropertyName(propertyName);
if (types.Count == 1)
{
writer.WriteValue(JsonSchemaBuilder.MapType(types[0]));
return;
}
writer.WriteStartArray();
foreach (JsonSchemaType jsonSchemaType in types)
{
writer.WriteValue(JsonSchemaBuilder.MapType(jsonSchemaType));
}
writer.WriteEndArray();
}
private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value)
{
if (value != null)
{
writer.WritePropertyName(propertyName);
writer.WriteValue(value);
}
}
}
}
#endif
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define CONTRACTS_FULL
#define CODE_ANALYSIS // For the SuppressMessage attribute
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.Research.ClousotRegression;
using System.Diagnostics.Contracts;
using System.Collections.Generic;
namespace TestWarningMasking
{
public class NotMasked
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly calling a method on a null reference 'o'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(o != null);")]
public string Nonnull(object o)
{
return o.ToString();
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"The length of the array may be negative", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(0 <= x);")]
public decimal[] ArrayCreation(int x)
{
return new decimal[x];
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Array access might be below the lower bound", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Array access might be above the upper bound", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possible use of a null array 's'", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(s != null);")]
[RegressionOutcome("Contract.Requires(0 <= index);")]
[RegressionOutcome("Contract.Requires(index < s.Length);")]
public string ArrayAccess(string[] s, int index)
{
return s[index];
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"assert unproven", PrimaryILOffset = 8, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(b >= 0);")]
public void Assertion(sbyte b)
{
Contract.Assert(b >= 0);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"requires unproven: o != null", PrimaryILOffset = 8, MethodILOffset = 3)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(o != null);")]
public void Precondition(object o)
{
Precondition_Internal(o);
}
private void Precondition_Internal(object o)
{
Contract.Requires(o != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"ensures unproven: Contract.Result<int>() < -222", PrimaryILOffset = 13, MethodILOffset = 24)]
[RegressionOutcome("Contract.Requires(k < -222);")]
public int Postcondition(int k)
{
Contract.Ensures(Contract.Result<int>() < -222);
return k;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Array access might be below the lower bound", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Array access might be above the upper bound", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Possibly calling a method on a null reference 'arr'", PrimaryILOffset = 2, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(arr != null);")]
[RegressionOutcome("Contract.Requires(0 <= z);")]
[RegressionOutcome("Contract.Requires(z < arr.Length);")]
public static string MaskFamily(string[] arr, int z)
{
var v = arr.ToString();
return arr[z] + v;
}
}
public class Masked
{
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-2-0")]
public string Nonnull(object o)
{
return o.ToString();
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "ArrayCreation-2-0")]
public decimal[] ArrayCreation(int x)
{
return new decimal[x];
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-3-0")]
[SuppressMessage("Microsoft.Contracts", "ArrayLowerBound-3-0")]
[SuppressMessage("Microsoft.Contracts", "ArrayUpperBound-3-0")]
public string ArrayAccess(string[] s, int index)
{
return s[index];
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Assert-8-0")]
public void Assertion(sbyte b)
{
Contract.Assert(b >= 0);
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Requires-8-3")]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as receiver)", PrimaryILOffset = 3, MethodILOffset = 0)]
public void Precondition(object o)
{
Precondition_Internal(o);
}
private void Precondition_Internal(object o)
{
Contract.Requires(o != null);
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Ensures-13-24")]
public int Postcondition(int k)
{
Contract.Ensures(Contract.Result<int>() < -222);
return k;
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull")]
[SuppressMessage("Microsoft.Contracts", "ArrayLowerBound")]
[RegressionOutcome(Outcome = ProofOutcome.Top, Message = @"Array access might be above the upper bound", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome(Outcome = ProofOutcome.True, Message = @"valid non-null reference (as array)", PrimaryILOffset = 10, MethodILOffset = 0)]
[RegressionOutcome("Contract.Requires(z < arr.Length);")]
public static string MaskFamily(string[] arr, int z)
{
var v = arr.ToString();
return arr[z] + v; // upper bound access is not masked
}
}
[SuppressMessage("Microsoft.Contracts", "Nonnull")]
[SuppressMessage("Microsoft.Contracts", "ArrayCreation")]
class MaskedClass
{
[ClousotRegressionTest]
public static string Null(object o)
{
return o.ToString();
}
[ClousotRegressionTest]
public static int[] NewArray(int size)
{
return new int[size];
}
}
}
namespace TestPreconditionWarningMask
{
public class RequiresAtCallMaskingTest
{
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "RequiresAtCall-Contract.ForAll(xs, x => x != null)")]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 'xs'",PrimaryILOffset=2,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(xs != null);")]
static public void ReadList(List<string> xs)
{
Contract.Requires(xs.Count > 10); // not masked
Contract.Requires(Contract.ForAll(xs, x => x != null)); // masked
// does nothing
}
}
public class F
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"requires unproven: xs.Count > 10",PrimaryILOffset=11,MethodILOffset=15)]
[RegressionOutcome("Contract.Requires(ys.Count > 10);")]
public void M(List<string> ys)
{
Contract.Requires(ys != null);
RequiresAtCallMaskingTest.ReadList(ys);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"requires unproven: xs.Count > 10",PrimaryILOffset=11,MethodILOffset=2)]
[RegressionOutcome("Contract.Requires(lista.Count > 10);")]
public void K(List<string> lista)
{
RequiresAtCallMaskingTest.ReadList(lista);
}
}
[ContractClass(typeof(SomeInterfaceContracts))]
public interface SomeInterface
{
[SuppressMessage("Microsoft.Contracts", "RequiresAtCall-myVarName > 123")]
void DoSomething(int x);
}
[ContractClassFor(typeof(SomeInterface))]
abstract class SomeInterfaceContracts
: SomeInterface
{
#region SomeInterface Members
void SomeInterface.DoSomething(int myVarName)
{
Contract.Requires(myVarName > 123); // masked
}
#endregion
}
public class UseMyInterface
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"Possibly calling a method on a null reference 's'",PrimaryILOffset=3,MethodILOffset=0)]
[RegressionOutcome("Contract.Requires(s != null);")]
public void CallDoSomething(SomeInterface s, int value)
{
s.DoSomething(value);
}
}
}
namespace UnMaskedPostcondition
{
[ContractClass(typeof(IContracts))]
public interface I
{
int F(int x);
}
[ContractClassFor(typeof(I))]
abstract public class IContracts : I
{
int I.F(int x)
{
Contract.Ensures(Contract.Result<int>() > 123);
throw new NotImplementedException();
}
}
public class FilterI : I
{
// unfiltered warning
[ClousotRegressionTest]
[RegressionOutcome("Contract.Assume(x > 123);")]
[RegressionOutcome("Contract.Requires(!(this is UnMaskedPostcondition.FilterI) || x > 123)")] // F: there is some extra info associated that we do not capture in the regression output
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"ensures unproven: Contract.Result<int>() > 123",PrimaryILOffset=10,MethodILOffset=6)]
public int F(int x)
{
return x;
}
}
}
namespace MaskedPostcondition
{
[ContractClass(typeof(IContracts))]
public interface I
{
[SuppressMessage("Microsoft.Contracts", "EnsuresInMethod-Contract.Result<int>() > 123")]
int F(int x);
}
[ContractClassFor(typeof(I))]
abstract public class IContracts : I
{
int I.F(int x)
{
Contract.Ensures(Contract.Result<int>() > 123);
throw new NotImplementedException();
}
}
public class FilterI : I
{
// Filtered warning
[ClousotRegressionTest]
//[RegressionOutcome("Contract.Requires(!(this is UnMaskedPostcondition.FilterI) || x > 123)")] // F: there is some extra info associated that we do not capture in the regression output
public int F(int x)
{
return x;
}
}
}
namespace ObsoleteSuppressWarnings
{
public class WarningMask
{
// Masked Warning
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-2-0")]
public int Masked(string s)
{
return s.Length;
}
// Warning not Masked, the suppress warning message is unused, we emit a string to the user
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message="Possibly calling a method on a null reference 's'. The static checker determined that the condition 's != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(s != null);",PrimaryILOffset=10,MethodILOffset=0)]
[SuppressMessage("Microsoft.Contracts", "Nonnull-2-0")]
[RegressionOutcome("Method ObsoleteSuppressWarnings.WarningMask.NotMasked_Warning: Unused suppression of a warning message: [SuppressMessage(\"Microsoft.Contracts\", \"Nonnull-2-0\")]")]
public int NotMasked_Warning(bool b, string s)
{
if (b)
return s.Length;
else
return 0;
}
// Error not Masked, the suppress warning message is unused, we emit a string to the user
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.False,Message="Calling a method on a null reference 's'. The static checker determined that the condition 's != null' should hold on entry. Nevertheless, the condition may be too strong for the callers. If you think it is ok, add a precondition to document it: Contract.Requires(s != null);",PrimaryILOffset=13,MethodILOffset=0)]
[SuppressMessage("Microsoft.Contracts", "Nonnull-2-0")]
[RegressionOutcome("Method ObsoleteSuppressWarnings.WarningMask.NotMasked_Error: Unused suppression of a warning message: [SuppressMessage(\"Microsoft.Contracts\", \"Nonnull-2-0\")]")]
public int NotMasked_Error(string s)
{
if (s == null)
return s.Length;
else
return 0;
}
}
[SuppressMessage("Microsoft.Contracts", "Nonnull")]
public class WarningMaskWithClassWideAttribute
{
// Masked Warning
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-1-0")]
[RegressionOutcome("Method ObsoleteSuppressWarnings.WarningMaskWithClassWideAttribute.Masked: Unused suppression of a warning message: [SuppressMessage(\"Microsoft.Contracts\", \"Nonnull-1-0\")]")]
public int Masked(string s)
{
return s.Length;
}
// Warning masked because of the class attribute, but the suppress warning message is unused so we emit a message to the user
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-1-0")]
[RegressionOutcome("Method ObsoleteSuppressWarnings.WarningMaskWithClassWideAttribute.NotMasked_Warning: Unused suppression of a warning message: [SuppressMessage(\"Microsoft.Contracts\", \"Nonnull-1-0\")]")]
public int NotMasked_Warning(bool b, string s)
{
if (b)
return s.Length;
else
return 0;
}
// Error masked because of the class attribute, the suppress warning message is unused so we emit a message to the user
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Nonnull-1-0")]
[RegressionOutcome("Method ObsoleteSuppressWarnings.WarningMaskWithClassWideAttribute.NotMasked_Error: Unused suppression of a warning message: [SuppressMessage(\"Microsoft.Contracts\", \"Nonnull-1-0\")]")]
public int NotMasked_Error(string s)
{
if (s == null)
return s.Length;
else
return 0;
}
}
}
namespace ObjectInvariantMasking
{
public class NotMasked
{
private object field;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this.field != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=1,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"invariant unproven: this.field != null",PrimaryILOffset=13,MethodILOffset=16)]
[RegressionOutcome("Contract.Requires(s != null);")]
public NotMasked(string s)
{
this.field = s;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=3,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"invariant unproven: this.field != null",PrimaryILOffset=13,MethodILOffset=8)]
[RegressionOutcome("Contract.Requires(z != null);")]
public void Set(int[] z)
{
this.field = z;
}
}
[SuppressMessage("Microsoft.Contracts", "InvariantInMethod-this.field != null")]
public class Masked
{
private object field;
[ContractInvariantMethod]
void ObjectInvariant()
{
Contract.Invariant(this.field != null);
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as receiver)",PrimaryILOffset=1,MethodILOffset=0)]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=10,MethodILOffset=0)]
public Masked(string s)
{
this.field = s;
}
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.True,Message=@"valid non-null reference (as field receiver)",PrimaryILOffset=3,MethodILOffset=0)]
public void Set(int[] z)
{
this.field = z;
}
}
}
namespace ShortCutForEnsuresMasking
{
public class MaskEnsures
{
[ClousotRegressionTest]
[RegressionOutcome(Outcome=ProofOutcome.Top,Message=@"ensures unproven: Contract.Result<int>() >= z * 3 + 12 * z * z",PrimaryILOffset=21,MethodILOffset=32)]
[RegressionOutcome("Contract.Requires(z >= (z * 3 + (12 * z) * z));")]
public int MaskMe(int z)
{
Contract.Ensures(Contract.Result<int>() >= z * 3 + 12 * z * z);
return z;
}
[ClousotRegressionTest]
[SuppressMessage("Microsoft.Contracts", "Ensures-Contract.Result<int>() >= z * 3 + 12 * z * z")]
public int Masked(int z)
{
Contract.Ensures(Contract.Result<int>() >= z * 3 + 12 * z * z);
return z;
}
}
}
namespace AlexeyR
{
public class ShouldMaskPreconditionSuggestion
{
[ClousotRegressionTest]
static void Caller(object arg)
{
// static checker suggests to add precondition here
Callee(arg);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Contracts", "RequiresAtCall-HardToProveCond(arg)")]
static void Callee(object arg)
{
Contract.Requires(HardToProveCond(arg));
}
[Pure]
static bool HardToProveCond(object arg)
{
return true;
}
}
}
namespace DaveSexton
{
public class Class1
{
[SuppressMessage("Microsoft.Contracts", "Contract.Requires(o != null);")]
public int Precondition(object o)
{
if (o.GetHashCode() > 123)
{
return -1;
}
return 4;
}
}
}
/*
// We do not sort warnings in regression ==> we cannot test it
namespace GroupBottoms
{
public class TooManyUnreached
{
public int x;
public int y;
public string s;
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(x > 0);
Contract.Invariant(y > 0);
Contract.Invariant(s.Length > 0);
}
[ClousotRegressionTest]
public TooManyUnreached()
{
}
[ClousotRegressionTest]
public int foo()
{
if (this.x == 0)
{
return 0;
}
return this.x + this.y;
}
}
}
*/
| |
using System;
using System.Collections.Generic;
using QuickGraph;
using System.Linq;
using System.Diagnostics;
using System.Windows;
namespace GraphSharp.Algorithms.Layout
{
public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam>, ILayoutAlgorithm<TVertex, TEdge, TGraph, TVertexInfo, TEdgeInfo>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters
{
protected readonly IDictionary<TVertex, TVertexInfo> vertexInfos = new Dictionary<TVertex, TVertexInfo>();
protected readonly IDictionary<TEdge, TEdgeInfo> edgeInfos = new Dictionary<TEdge, TEdgeInfo>();
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph )
: base( visitedGraph, null, null ) { }
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions,
TParam oldParameters )
: base( visitedGraph, vertexPositions, oldParameters )
{
}
#region ILayoutAlgorithm<TVertex,TEdge,TGraph,TVertexInfo,TEdgeInfo> Members
public IDictionary<TVertex, TVertexInfo> VertexInfos
{
get { return vertexInfos; }
}
public IDictionary<TEdge, TEdgeInfo> EdgeInfos
{
get { return edgeInfos; }
}
protected override ILayoutIterationEventArgs<TVertex> CreateLayoutIterationEventArgs( int iteration, double statusInPercent, string message, IDictionary<TVertex, Point> vertexPositions )
{
return new LayoutIterationEventArgs<TVertex, TEdge, TVertexInfo, TEdgeInfo>( iteration, statusInPercent, message, vertexPositions, vertexInfos, edgeInfos );
}
public new event LayoutIterationEndedEventHandler<TVertex, TEdge, TVertexInfo, TEdgeInfo> IterationEnded;
public override object GetVertexInfo( TVertex vertex )
{
TVertexInfo info;
if ( VertexInfos.TryGetValue( vertex, out info ) )
return info;
return null;
}
public override object GetEdgeInfo( TEdge edge )
{
TEdgeInfo info;
if ( EdgeInfos.TryGetValue( edge, out info ) )
return info;
return null;
}
#endregion
}
/// <summary>
/// Use this class as a base class for your layout algorithm
/// if it's parameter class has a default contstructor.
/// </summary>
/// <typeparam name="TVertex">The type of the vertices.</typeparam>
/// <typeparam name="TEdge">The type of the edges.</typeparam>
/// <typeparam name="TGraph">The type of the graph.</typeparam>
/// <typeparam name="TParam">The type of the parameters. Must be based on the LayoutParametersBase.</typeparam>
public abstract class DefaultParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters, new()
{
protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph)
: base(visitedGraph)
{
}
protected DefaultParameterizedLayoutAlgorithmBase(TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions, TParam oldParameters)
: base(visitedGraph, vertexPositions, oldParameters)
{
}
protected override TParam DefaultParameters
{
get { return new TParam(); }
}
}
/// <typeparam name="TVertex">Type of the vertices.</typeparam>
/// <typeparam name="TEdge">Type of the edges.</typeparam>
/// <typeparam name="TGraph">Type of the graph.</typeparam>
/// <typeparam name="TParam">Type of the parameters. Must be based on the LayoutParametersBase.</typeparam>
public abstract class ParameterizedLayoutAlgorithmBase<TVertex, TEdge, TGraph, TParam> : LayoutAlgorithmBase<TVertex, TEdge, TGraph>, IParameterizedLayoutAlgorithm<TParam>
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : IVertexAndEdgeListGraph<TVertex, TEdge>
where TParam : class, ILayoutParameters
{
#region Properties
/// <summary>
/// Parameters of the algorithm. For more information see <see cref="LayoutParametersBase"/>.
/// </summary>
public TParam Parameters { get; protected set; }
public ILayoutParameters GetParameters()
{
return Parameters;
}
public TraceSource TraceSource { get; protected set; }
#endregion
#region Constructors
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph )
: this( visitedGraph, null, null ) { }
protected ParameterizedLayoutAlgorithmBase( TGraph visitedGraph, IDictionary<TVertex, Point> vertexPositions,
TParam oldParameters )
: base( visitedGraph, vertexPositions )
{
InitParameters( oldParameters );
TraceSource = new TraceSource( "LayoutAlgorithm", SourceLevels.All );
}
#endregion
#region Initializers
protected abstract TParam DefaultParameters { get; }
/// <summary>
/// Initializes the parameters (cloning or creating new parameter object with default values).
/// </summary>
/// <param name="oldParameters">Parameters from a prevorious layout. If it is null,
/// the parameters will be set to the default ones.</param>
protected void InitParameters( TParam oldParameters )
{
if (oldParameters == null)
Parameters = DefaultParameters;
else
{
Parameters = (TParam)oldParameters.Clone();
}
}
/// <summary>
/// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions.
/// It does NOT modify the position of the other vertices.
///
/// It generates an <code>IterationEnded</code> event.
///
/// Bounding box:
/// x coordinates: double.Epsilon - <code>width</code>
/// y coordinates: double.Epsilon - <code>height</code>
/// </summary>
/// <param name="width">Width of the bounding box.</param>
/// <param name="height">Height of the bounding box.</param>
protected virtual void InitializeWithRandomPositions( double width, double height )
{
InitializeWithRandomPositions( width, height, 0, 0 );
}
/// <summary>
/// Initializes the positions of the vertices. Assign a random position inside the 'bounding box' to the vertices without positions.
/// It does NOT modify the position of the other vertices.
///
/// It generates an <code>IterationEnded</code> event.
///
/// Bounding box:
/// x coordinates: double.Epsilon - <code>width</code>
/// y coordinates: double.Epsilon - <code>height</code>
/// </summary>
/// <param name="width">Width of the bounding box.</param>
/// <param name="height">Height of the bounding box.</param>
/// <param name="translate_x">Translates the generated x coordinate.</param>
/// <param name="translate_y">Translates the generated y coordinate.</param>
protected virtual void InitializeWithRandomPositions( double width, double height, double translate_x, double translate_y )
{
var rnd = new Random( DateTime.Now.Millisecond );
//initialize with random position
foreach ( TVertex v in VisitedGraph.Vertices )
{
//for vertices without assigned position
if ( !VertexPositions.ContainsKey( v ) )
{
VertexPositions[v] =
new Point(
Math.Max( double.Epsilon, rnd.NextDouble() * width + translate_x ),
Math.Max( double.Epsilon, rnd.NextDouble() * height + translate_y ) );
}
}
}
protected virtual void NormalizePositions()
{
lock ( SyncRoot )
{
NormalizePositions( VertexPositions );
}
}
protected static void NormalizePositions( IDictionary<TVertex, Point> vertexPositions )
{
if ( vertexPositions == null || vertexPositions.Count == 0 )
return;
//get the topLeft position
var topLeft = new Point( float.PositiveInfinity, float.PositiveInfinity );
foreach ( var pos in vertexPositions.Values.ToArray() )
{
topLeft.X = Math.Min( topLeft.X, pos.X );
topLeft.Y = Math.Min( topLeft.Y, pos.Y );
}
//translate with the topLeft position
foreach ( var v in vertexPositions.Keys.ToArray() )
{
var pos = vertexPositions[v];
pos.X -= topLeft.X;
pos.Y -= topLeft.Y;
vertexPositions[v] = pos;
}
}
#endregion
protected void OnIterationEnded( int iteration, double statusInPercent, string message, bool normalizePositions )
{
//copy the actual positions
IDictionary<TVertex, Point> vertexPositions;
lock ( SyncRoot )
{
vertexPositions = new Dictionary<TVertex, Point>( VertexPositions );
}
if ( normalizePositions )
NormalizePositions( vertexPositions );
var args = CreateLayoutIterationEventArgs( iteration, statusInPercent, message, vertexPositions );
OnIterationEnded( args );
}
protected virtual ILayoutIterationEventArgs<TVertex> CreateLayoutIterationEventArgs( int iteration, double statusInPercent, string message, IDictionary<TVertex, Point> vertexPositions )
{
return new LayoutIterationEventArgs<TVertex, TEdge>( iteration, statusInPercent, message, vertexPositions );
}
}
}
| |
/*
* Copyright 2002-2010 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.
*/
using System;
using Quartz;
using Quartz.Impl;
using Spring.Objects.Factory;
using Spring.Objects.Factory.Config;
using Spring.Objects.Support;
namespace Spring.Scheduling.Quartz
{
/// <summary>
/// IFactoryObject that exposes a JobDetail object that delegates job execution
/// to a specified (static or non-static) method. Avoids the need to implement
/// a one-line Quartz Job that just invokes an existing service method.
/// </summary>
/// <remarks>
/// <p>
/// Derived from ArgumentConverting MethodInvoker to share common properties and behavior
/// with MethodInvokingFactoryObject.
/// </p>
/// <p>
/// Supports both concurrently running jobs and non-currently running
/// ones through the "concurrent" property. Jobs created by this
/// MethodInvokingJobDetailFactoryObject are by default volatile and durable
/// (according to Quartz terminology).
/// </p>
/// <p><b>NOTE: JobDetails created via this FactoryObject are <i>not</i>
/// serializable and thus not suitable for persistent job stores.</b>
/// You need to implement your own Quartz Job as a thin wrapper for each case
/// where you want a persistent job to delegate to a specific service method.
/// </p>
/// </remarks>
/// <author>Juergen Hoeller</author>
/// <author>Alef Arendsen</author>
/// <seealso cref="Concurrent" />
/// <seealso cref="MethodInvokingFactoryObject" />
public class MethodInvokingJobDetailFactoryObject : ArgumentConvertingMethodInvoker,
IObjectFactoryAware,
IFactoryObject,
IObjectNameAware,
IInitializingObject
{
private string name;
private string group;
private bool concurrent = true;
private string[] jobListenerNames;
private string targetObjectName;
private string objectName;
private JobDetailImpl jobDetail;
private IObjectFactory objectFactory;
/// <summary>
/// Initializes a new instance of the <see cref="MethodInvokingJobDetailFactoryObject"/> class.
/// </summary>
public MethodInvokingJobDetailFactoryObject()
{
group = SchedulerConstants.DefaultGroup;
}
/// <summary>
/// Set the name of the job.
/// Default is the object name of this FactoryObject.
/// </summary>
/// <seealso cref="Name" />
public virtual string Name
{
set { name = value; }
}
/// <summary>
/// Set the group of the job.
/// Default is the default group of the Scheduler.
/// </summary>
/// <seealso cref="Group" />
/// <seealso cref="SchedulerConstants.DefaultGroup" />
public virtual string Group
{
set { group = value; }
}
/// <summary>
/// Specify whether or not multiple jobs should be run in a concurrent
/// fashion. The behavior when one does not want concurrent jobs to be
/// executed is realized through adding the <see cref="DisallowConcurrentExecutionAttribute" /> attribute.
/// More information on stateful versus stateless jobs can be found
/// <a href="http://www.opensymphony.com/quartz/tutorial.html#jobsMore">here</a>.
/// <p>
/// The default setting is to run jobs concurrently.
/// </p>
/// </summary>
public virtual bool Concurrent
{
set { concurrent = value; }
}
/// <summary>
/// Gets the job detail.
/// </summary>
/// <value>The job detail.</value>
protected IJobDetail JobDetail
{
get { return jobDetail; }
}
/// <summary>
/// Set a list of JobListener names for this job, referring to
/// non-global JobListeners registered with the Scheduler.
/// </summary>
/// <remarks>
/// A JobListener name always refers to the name returned
/// by the JobListener implementation.
/// </remarks>
/// <seealso cref="SchedulerAccessor.JobListeners" />
/// <seealso cref="IJobListener.Name" />
public virtual string[] JobListenerNames
{
set { jobListenerNames = value; }
}
/// <summary>
/// Set the name of the object in the object factory that created this object.
/// </summary>
/// <value>The name of the object in the factory.</value>
/// <remarks>
/// Invoked after population of normal object properties but before an init
/// callback like <see cref="Spring.Objects.Factory.IInitializingObject"/>'s
/// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/>
/// method or a custom init-method.
/// </remarks>
public virtual string ObjectName
{
set { objectName = value; }
}
/// <summary>
/// Set the name of the target object in the Spring object factory.
/// </summary>
/// <remarks>
/// This is an alternative to specifying TargetObject
/// allowing for non-singleton objects to be invoked. Note that specified
/// "TargetObject" and "TargetType" values will
/// override the corresponding effect of this "TargetObjectName" setting
///(i.e. statically pre-define the object type or even the target object).
/// </remarks>
public string TargetObjectName
{
set { targetObjectName = value; }
}
/// <summary>
/// Sets the object factory.
/// </summary>
/// <value>The object factory.</value>
public IObjectFactory ObjectFactory
{
set { objectFactory = value; }
}
/// <summary>
/// Return an instance (possibly shared or independent) of the object
/// managed by this factory.
/// </summary>
/// <returns>
/// An instance (possibly shared or independent) of the object managed by
/// this factory.
/// </returns>
/// <remarks>
/// <note type="caution">
/// If this method is being called in the context of an enclosing IoC container and
/// returns <see langword="null"/>, the IoC container will consider this factory
/// object as not being fully initialized and throw a corresponding (and most
/// probably fatal) exception.
/// </note>
/// </remarks>
public virtual object GetObject()
{
return jobDetail;
}
/// <summary>
/// Return the <see cref="System.Type"/> of object that this
/// <see cref="Spring.Objects.Factory.IFactoryObject"/> creates, or
/// <see langword="null"/> if not known in advance.
/// </summary>
/// <value></value>
public virtual Type ObjectType
{
get
{
if (targetObjectName != null)
{
if (objectFactory == null)
{
throw new InvalidOperationException("ObjectFactory must be set when using 'TargetObjectName'");
}
return objectFactory.GetType(targetObjectName);
}
return typeof(IJobDetail);
}
}
/// <summary>
/// Is the object managed by this factory a singleton or a prototype?
/// </summary>
/// <value></value>
public virtual bool IsSingleton
{
get { return true; }
}
/// <summary>
/// Invoked by an <see cref="Spring.Objects.Factory.IObjectFactory"/>
/// after it has injected all of an object's dependencies.
/// </summary>
/// <remarks>
/// <p>
/// This method allows the object instance to perform the kind of
/// initialization only possible when all of it's dependencies have
/// been injected (set), and to throw an appropriate exception in the
/// event of misconfiguration.
/// </p>
/// <p>
/// Please do consult the class level documentation for the
/// <see cref="Spring.Objects.Factory.IObjectFactory"/> interface for a
/// description of exactly <i>when</i> this method is invoked. In
/// particular, it is worth noting that the
/// <see cref="Spring.Objects.Factory.IObjectFactoryAware"/>
/// and <see cref="Spring.Context.IApplicationContextAware"/>
/// callbacks will have been invoked <i>prior</i> to this method being
/// called.
/// </p>
/// </remarks>
/// <exception cref="System.Exception">
/// In the event of misconfiguration (such as the failure to set a
/// required property) or if initialization fails.
/// </exception>
public virtual void AfterPropertiesSet()
{
Prepare();
// Use specific name if given, else fall back to object name.
string jobDetailName = name ?? objectName;
// Consider the concurrent flag to choose between stateful and stateless job.
Type jobType = (concurrent ? typeof (MethodInvokingJob) : typeof (StatefulMethodInvokingJob));
// Build JobDetail instance.
jobDetail = new JobDetailImpl(jobDetailName, group, jobType);
jobDetail.JobDataMap.Put("methodInvoker", this);
jobDetail.Durable = true;
// job listeners through configuration are no longer supported
if (jobListenerNames != null && jobListenerNames.Length > 0)
{
throw new InvalidOperationException("Non-global IJobListeners not supported on Quartz 2 - " +
"manually register a Matcher against the Quartz ListenerManager instead");
}
PostProcessJobDetail(jobDetail);
}
/// <summary>
/// Callback for post-processing the JobDetail to be exposed by this FactoryObject.
/// <p>
/// The default implementation is empty. Can be overridden in subclasses.
/// </p>
/// </summary>
/// <param name="detail">the JobDetail prepared by this FactoryObject</param>
protected virtual void PostProcessJobDetail(IJobDetail detail)
{
}
}
}
| |
/*
* 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 Nini.Config;
using log4net;
using System;
using System.Reflection;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Services.UserAccountService;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Framework.ServiceAuth;
using OpenMetaverse;
namespace OpenSim.Server.Handlers.UserAccounts
{
public class UserAccountServerPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IUserAccountService m_UserAccountService;
private bool m_AllowCreateUser = false;
private bool m_AllowSetAccount = false;
public UserAccountServerPostHandler(IUserAccountService service)
: this(service, null, null) {}
public UserAccountServerPostHandler(IUserAccountService service, IConfig config, IServiceAuth auth) :
base("POST", "/accounts", auth)
{
m_UserAccountService = service;
if (config != null)
{
m_AllowCreateUser = config.GetBoolean("AllowCreateUser", m_AllowCreateUser);
m_AllowSetAccount = config.GetBoolean("AllowSetAccount", m_AllowSetAccount);
}
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
// We need to check the authorization header
//httpRequest.Headers["authorization"] ...
//m_log.DebugFormat("[XXX]: query String: {0}", body);
string method = string.Empty;
try
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
method = request["METHOD"].ToString();
switch (method)
{
case "createuser":
if (m_AllowCreateUser)
return CreateUser(request);
else
return FailureResult();
case "getaccount":
return GetAccount(request);
case "getaccounts":
return GetAccounts(request);
case "getmultiaccounts":
return GetMultiAccounts(request);
case "setaccount":
if (m_AllowSetAccount)
return StoreAccount(request);
else
return FailureResult();
}
m_log.DebugFormat("[USER SERVICE HANDLER]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.DebugFormat("[USER SERVICE HANDLER]: Exception in method {0}: {1}", method, e);
}
return FailureResult();
}
byte[] GetAccount(Dictionary<string, object> request)
{
UserAccount account = null;
UUID scopeID = UUID.Zero;
Dictionary<string, object> result = new Dictionary<string, object>();
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
{
result["result"] = "null";
return ResultToBytes(result);
}
if (request.ContainsKey("UserID") && request["UserID"] != null)
{
UUID userID;
if (UUID.TryParse(request["UserID"].ToString(), out userID))
account = m_UserAccountService.GetUserAccount(scopeID, userID);
}
else if (request.ContainsKey("PrincipalID") && request["PrincipalID"] != null)
{
UUID userID;
if (UUID.TryParse(request["PrincipalID"].ToString(), out userID))
account = m_UserAccountService.GetUserAccount(scopeID, userID);
}
else if (request.ContainsKey("Email") && request["Email"] != null)
{
account = m_UserAccountService.GetUserAccount(scopeID, request["Email"].ToString());
}
else if (request.ContainsKey("FirstName") && request.ContainsKey("LastName") &&
request["FirstName"] != null && request["LastName"] != null)
{
account = m_UserAccountService.GetUserAccount(scopeID, request["FirstName"].ToString(), request["LastName"].ToString());
}
if (account == null)
{
result["result"] = "null";
}
else
{
result["result"] = account.ToKeyValuePairs();
}
return ResultToBytes(result);
}
byte[] GetAccounts(Dictionary<string, object> request)
{
if (!request.ContainsKey("query"))
return FailureResult();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
string query = request["query"].ToString();
List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, query);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((accounts == null) || ((accounts != null) && (accounts.Count == 0)))
{
result["result"] = "null";
}
else
{
int i = 0;
foreach (UserAccount acc in accounts)
{
Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs();
result["account" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] GetMultiAccounts(Dictionary<string, object> request)
{
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
if (!request.ContainsKey("IDS"))
{
m_log.DebugFormat("[USER SERVICE HANDLER]: GetMultiAccounts called without required uuids argument");
return FailureResult();
}
if (!(request["IDS"] is List<string>))
{
m_log.DebugFormat("[USER SERVICE HANDLER]: GetMultiAccounts input argument was of unexpected type {0}", request["IDS"].GetType().ToString());
return FailureResult();
}
List<string> userIDs = (List<string>)request["IDS"];
List<UserAccount> accounts = m_UserAccountService.GetUserAccounts(scopeID, userIDs);
Dictionary<string, object> result = new Dictionary<string, object>();
if ((accounts == null) || ((accounts != null) && (accounts.Count == 0)))
{
result["result"] = "null";
}
else
{
int i = 0;
foreach (UserAccount acc in accounts)
{
if(acc == null)
continue;
Dictionary<string, object> rinfoDict = acc.ToKeyValuePairs();
result["account" + i] = rinfoDict;
i++;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] StoreAccount(Dictionary<string, object> request)
{
UUID principalID = UUID.Zero;
if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID))
return FailureResult();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
UserAccount existingAccount = m_UserAccountService.GetUserAccount(scopeID, principalID);
if (existingAccount == null)
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
if (request.ContainsKey("FirstName"))
existingAccount.FirstName = request["FirstName"].ToString();
if (request.ContainsKey("LastName"))
existingAccount.LastName = request["LastName"].ToString();
if (request.ContainsKey("Email"))
existingAccount.Email = request["Email"].ToString();
int created = 0;
if (request.ContainsKey("Created") && int.TryParse(request["Created"].ToString(), out created))
existingAccount.Created = created;
int userLevel = 0;
if (request.ContainsKey("UserLevel") && int.TryParse(request["UserLevel"].ToString(), out userLevel))
existingAccount.UserLevel = userLevel;
int userFlags = 0;
if (request.ContainsKey("UserFlags") && int.TryParse(request["UserFlags"].ToString(), out userFlags))
existingAccount.UserFlags = userFlags;
if (request.ContainsKey("UserTitle"))
existingAccount.UserTitle = request["UserTitle"].ToString();
if (!m_UserAccountService.StoreUserAccount(existingAccount))
{
m_log.ErrorFormat(
"[USER ACCOUNT SERVER POST HANDLER]: Account store failed for account {0} {1} {2}",
existingAccount.FirstName, existingAccount.LastName, existingAccount.PrincipalID);
return FailureResult();
}
result["result"] = existingAccount.ToKeyValuePairs();
return ResultToBytes(result);
}
byte[] CreateUser(Dictionary<string, object> request)
{
if (! request.ContainsKey("FirstName")
&& request.ContainsKey("LastName")
&& request.ContainsKey("Password"))
return FailureResult();
Dictionary<string, object> result = new Dictionary<string, object>();
UUID scopeID = UUID.Zero;
if (request.ContainsKey("ScopeID") && !UUID.TryParse(request["ScopeID"].ToString(), out scopeID))
return FailureResult();
UUID principalID = UUID.Random();
if (request.ContainsKey("PrincipalID") && !UUID.TryParse(request["PrincipalID"].ToString(), out principalID))
return FailureResult();
string firstName = request["FirstName"].ToString();
string lastName = request["LastName"].ToString();
string password = request["Password"].ToString();
string email = "";
if (request.ContainsKey("Email"))
email = request["Email"].ToString();
string model = "";
if (request.ContainsKey("Model"))
model = request["Model"].ToString();
UserAccount createdUserAccount = null;
if (m_UserAccountService is UserAccountService)
createdUserAccount
= ((UserAccountService)m_UserAccountService).CreateUser(
scopeID, principalID, firstName, lastName, password, email, model);
if (createdUserAccount == null)
return FailureResult();
result["result"] = createdUserAccount.ToKeyValuePairs();
return ResultToBytes(result);
}
private byte[] SuccessResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Success"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] FailureResult()
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "result", "");
result.AppendChild(doc.CreateTextNode("Failure"));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
private byte[] ResultToBytes(Dictionary<string, object> result)
{
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Resources;
namespace MarioObjects
{
class Media
{
public static Boolean SOUND_ENABLE = false;
public enum SoundType { ST_level1, ST_level2, ST_Brick, ST_Coin, ST_Jump, ST_Block, ST_Stomp, ST_Mush, ST_FireBall };
private FMOD.System soundsystem = null;
private FMOD.Sound s_level1 = null;
private FMOD.Sound s_level2 = null;
private FMOD.Sound s_brick = null;
private FMOD.Sound s_coin = null;
private FMOD.Sound s_jump = null;
private FMOD.Sound s_block = null;
private FMOD.Sound s_stomp = null;
private FMOD.Sound s_mush = null;
private FMOD.Sound s_fireball = null;
private FMOD.Channel channel = null;
public static Media instance=null;
public void Destroy()
{
FMOD.RESULT result;
result = s_level1.release();
ERRCHECK(result);
result = s_level2.release();
ERRCHECK(result);
result = s_jump.release();
ERRCHECK(result);
result = s_coin.release();
ERRCHECK(result);
result = s_brick.release();
ERRCHECK(result);
result = s_block.release();
ERRCHECK(result);
result = s_stomp.release();
ERRCHECK(result);
result = s_mush.release();
ERRCHECK(result);
result = s_fireball.release();
ERRCHECK(result);
result = soundsystem.close();
ERRCHECK(result);
result = soundsystem.release();
ERRCHECK(result);
}
public static Media Instance
{
get
{
if (instance == null)
instance = new Media();
return instance;
}
}
public void UpdateSound(string name,ref FMOD.Sound s,Boolean Loop)
{
FMOD.RESULT result;
string strNameSpace =
System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
Stream str = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(strNameSpace + ".Sounds." + name);
//Block = new Bitmap(str);
byte[] Arr = new byte[str.Length];
str.Read(Arr, 0, (int)str.Length);
FMOD.CREATESOUNDEXINFO inf = new FMOD.CREATESOUNDEXINFO();
inf.cbsize = Marshal.SizeOf(inf);
inf.length = (uint)str.Length;
result = soundsystem.createSound(Arr, FMOD.MODE.SOFTWARE | FMOD.MODE.OPENMEMORY | FMOD.MODE._3D, ref inf, ref s);
ERRCHECK(result);
if (!Loop)
s.setMode(FMOD.MODE.LOOP_OFF);
else
s.setMode(FMOD.MODE.LOOP_NORMAL);
ERRCHECK(result);
}
public void LoadFromResource()
{
UpdateSound("level1.mp3", ref s_level1,true);
UpdateSound("level2.mp3", ref s_level2, true);
UpdateSound("brick.wav", ref s_brick, false);
UpdateSound("coin.wav", ref s_coin, false);
UpdateSound("jump.wav", ref s_jump, false);
UpdateSound("block.wav", ref s_block, false);
UpdateSound("stomp.wav", ref s_stomp, false);
UpdateSound("mush.wav", ref s_mush, false);
UpdateSound("fireball.wav", ref s_fireball, false);
}
public FMOD.Sound GetSound(SoundType type)
{
switch (type)
{
case SoundType.ST_level1:
{ return s_level1; }
case SoundType.ST_level2:
{ return s_level2; }
case SoundType.ST_Brick:
{ return s_brick; }
case SoundType.ST_Coin:
{ return s_coin; }
case SoundType.ST_Jump:
{ return s_jump; }
case SoundType.ST_Block:
{ return s_block; }
case SoundType.ST_Stomp:
{ return s_stomp; }
case SoundType.ST_Mush:
{ return s_mush; }
case SoundType.ST_FireBall:
{ return s_fireball; }
}
return null;
}
public void PlayInnerSound(SoundType type)
{
FMOD.RESULT result;
FMOD.Sound sound = GetSound(type);
if (sound != null)
{
result = soundsystem.playSound(FMOD.CHANNELINDEX.FREE, sound, false, ref channel);
ERRCHECK(result);
if (type == SoundType.ST_level1 || type == SoundType.ST_level2)
channel.setVolume(1f);
else
channel.setVolume(0.15f);
}
}
public static void PlaySound(SoundType type)
{
if (!SOUND_ENABLE)
return;
Instance.PlayInnerSound(type);
}
public Media()
{
uint version = 0;
FMOD.RESULT result;
/*
Create a System object and initialize.
*/
result = FMOD.Factory.System_Create(ref soundsystem);
ERRCHECK(result);
result = soundsystem.getVersion(ref version);
ERRCHECK(result);
if (version < FMOD.VERSION.number)
{
MessageBox.Show("Error! You are using an old version of FMOD " + version.ToString("X") + ". This program requires " + FMOD.VERSION.number.ToString("X") + ".");
Application.Exit();
}
result = soundsystem.init(32, FMOD.INITFLAGS.NORMAL, (IntPtr)null);
ERRCHECK(result);
LoadFromResource();
}
private void ERRCHECK(FMOD.RESULT result)
{
if (result != FMOD.RESULT.OK)
{
//timer.Stop();
//MessageBox.Show("FMOD error! " + result + " - " + FMOD.Error.String(result));
//Environment.Exit(-1);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Lucene.Net.Documents;
using Lucene.Net.Search;
namespace Lucene.Net.Index
{
using Lucene.Net.Randomized.Generators;
using NUnit.Framework;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Analyzer = Lucene.Net.Analysis.Analyzer;
using BytesRef = Lucene.Net.Util.BytesRef;
using CannedTokenStream = Lucene.Net.Analysis.CannedTokenStream;
using Directory = Lucene.Net.Store.Directory;
using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator;
using Document = Documents.Document;
using English = Lucene.Net.Util.English;
using Field = Field;
using FieldType = FieldType;
using IntField = IntField;
using IOUtils = Lucene.Net.Util.IOUtils;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer;
using MockPayloadAnalyzer = Lucene.Net.Analysis.MockPayloadAnalyzer;
using StringField = StringField;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
using Token = Lucene.Net.Analysis.Token;
using TokenStream = Lucene.Net.Analysis.TokenStream;
// TODO: we really need to test indexingoffsets, but then getting only docs / docs + freqs.
// not all codecs store prx separate...
// TODO: fix sep codec to index offsets so we can greatly reduce this list!
[TestFixture]
public class TestPostingsOffsets : LuceneTestCase
{
internal IndexWriterConfig Iwc;
[SetUp]
public override void SetUp()
{
base.SetUp();
Iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()));
}
[Test]
public virtual void TestBasic()
{
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Iwc);
Document doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
if (Random().NextBoolean())
{
ft.StoreTermVectors = true;
ft.StoreTermVectorPositions = Random().NextBoolean();
ft.StoreTermVectorOffsets = Random().NextBoolean();
}
Token[] tokens = new Token[] { MakeToken("a", 1, 0, 6), MakeToken("b", 1, 8, 9), MakeToken("a", 1, 9, 17), MakeToken("c", 1, 19, 50) };
doc.Add(new Field("content", new CannedTokenStream(tokens), ft));
w.AddDocument(doc);
IndexReader r = w.Reader;
w.Dispose();
DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("a"));
Assert.IsNotNull(dp);
Assert.AreEqual(0, dp.NextDoc());
Assert.AreEqual(2, dp.Freq());
Assert.AreEqual(0, dp.NextPosition());
Assert.AreEqual(0, dp.StartOffset());
Assert.AreEqual(6, dp.EndOffset());
Assert.AreEqual(2, dp.NextPosition());
Assert.AreEqual(9, dp.StartOffset());
Assert.AreEqual(17, dp.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc());
dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("b"));
Assert.IsNotNull(dp);
Assert.AreEqual(0, dp.NextDoc());
Assert.AreEqual(1, dp.Freq());
Assert.AreEqual(1, dp.NextPosition());
Assert.AreEqual(8, dp.StartOffset());
Assert.AreEqual(9, dp.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc());
dp = MultiFields.GetTermPositionsEnum(r, null, "content", new BytesRef("c"));
Assert.IsNotNull(dp);
Assert.AreEqual(0, dp.NextDoc());
Assert.AreEqual(1, dp.Freq());
Assert.AreEqual(3, dp.NextPosition());
Assert.AreEqual(19, dp.StartOffset());
Assert.AreEqual(50, dp.EndOffset());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc());
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestSkipping()
{
DoTestNumbers(false);
}
[Test]
public virtual void TestPayloads()
{
DoTestNumbers(true);
}
public virtual void DoTestNumbers(bool withPayloads)
{
Directory dir = NewDirectory();
Analyzer analyzer = withPayloads ? (Analyzer)new MockPayloadAnalyzer() : new MockAnalyzer(Random());
Iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer);
Iwc.SetMergePolicy(NewLogMergePolicy()); // will rely on docids a bit for skipping
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Iwc);
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
if (Random().NextBoolean())
{
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = Random().NextBoolean();
ft.StoreTermVectorPositions = Random().NextBoolean();
}
int numDocs = AtLeast(500);
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
doc.Add(new Field("numbers", English.IntToEnglish(i), ft));
doc.Add(new Field("oddeven", (i % 2) == 0 ? "even" : "odd", ft));
doc.Add(new StringField("id", "" + i, Field.Store.NO));
w.AddDocument(doc);
}
IndexReader reader = w.Reader;
w.Dispose();
string[] terms = new string[] { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "hundred" };
foreach (string term in terms)
{
DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(reader, null, "numbers", new BytesRef(term));
int doc;
while ((doc = dp.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
string storedNumbers = reader.Document(doc).Get("numbers");
int freq = dp.Freq();
for (int i = 0; i < freq; i++)
{
dp.NextPosition();
int start = dp.StartOffset();
Debug.Assert(start >= 0);
int end = dp.EndOffset();
Debug.Assert(end >= 0 && end >= start);
// check that the offsets correspond to the term in the src text
Assert.IsTrue(storedNumbers.Substring(start, end - start).Equals(term));
if (withPayloads)
{
// check that we have a payload and it starts with "pos"
Assert.IsNotNull(dp.Payload);
BytesRef payload = dp.Payload;
Assert.IsTrue(payload.Utf8ToString().StartsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
}
// check we can skip correctly
int numSkippingTests = AtLeast(50);
for (int j = 0; j < numSkippingTests; j++)
{
int num = TestUtil.NextInt(Random(), 100, Math.Min(numDocs - 1, 999));
DocsAndPositionsEnum dp = MultiFields.GetTermPositionsEnum(reader, null, "numbers", new BytesRef("hundred"));
int doc = dp.Advance(num);
Assert.AreEqual(num, doc);
int freq = dp.Freq();
for (int i = 0; i < freq; i++)
{
string storedNumbers = reader.Document(doc).Get("numbers");
dp.NextPosition();
int start = dp.StartOffset();
Debug.Assert(start >= 0);
int end = dp.EndOffset();
Debug.Assert(end >= 0 && end >= start);
// check that the offsets correspond to the term in the src text
Assert.IsTrue(storedNumbers.Substring(start, end - start).Equals("hundred"));
if (withPayloads)
{
// check that we have a payload and it starts with "pos"
Assert.IsNotNull(dp.Payload);
BytesRef payload = dp.Payload;
Assert.IsTrue(payload.Utf8ToString().StartsWith("pos:"));
} // note: withPayloads=false doesnt necessarily mean we dont have them from MockAnalyzer!
}
}
// check that other fields (without offsets) work correctly
for (int i = 0; i < numDocs; i++)
{
DocsEnum dp = MultiFields.GetTermDocsEnum(reader, null, "id", new BytesRef("" + i), 0);
Assert.AreEqual(i, dp.NextDoc());
Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, dp.NextDoc());
}
reader.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestRandom()
{
// token -> docID -> tokens
IDictionary<string, IDictionary<int?, IList<Token>>> actualTokens = new Dictionary<string, IDictionary<int?, IList<Token>>>();
Directory dir = NewDirectory();
RandomIndexWriter w = new RandomIndexWriter(Random(), dir, Iwc);
int numDocs = AtLeast(20);
//final int numDocs = AtLeast(5);
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
// TODO: randomize what IndexOptions we use; also test
// changing this up in one IW buffered segment...:
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
if (Random().NextBoolean())
{
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = Random().NextBoolean();
ft.StoreTermVectorPositions = Random().NextBoolean();
}
for (int docCount = 0; docCount < numDocs; docCount++)
{
Document doc = new Document();
doc.Add(new IntField("id", docCount, Field.Store.NO));
IList<Token> tokens = new List<Token>();
int numTokens = AtLeast(100);
//final int numTokens = AtLeast(20);
int pos = -1;
int offset = 0;
//System.out.println("doc id=" + docCount);
for (int tokenCount = 0; tokenCount < numTokens; tokenCount++)
{
string text;
if (Random().NextBoolean())
{
text = "a";
}
else if (Random().NextBoolean())
{
text = "b";
}
else if (Random().NextBoolean())
{
text = "c";
}
else
{
text = "d";
}
int posIncr = Random().NextBoolean() ? 1 : Random().Next(5);
if (tokenCount == 0 && posIncr == 0)
{
posIncr = 1;
}
int offIncr = Random().NextBoolean() ? 0 : Random().Next(5);
int tokenOffset = Random().Next(5);
Token token = MakeToken(text, posIncr, offset + offIncr, offset + offIncr + tokenOffset);
if (!actualTokens.ContainsKey(text))
{
actualTokens[text] = new Dictionary<int?, IList<Token>>();
}
IDictionary<int?, IList<Token>> postingsByDoc = actualTokens[text];
if (!postingsByDoc.ContainsKey(docCount))
{
postingsByDoc[docCount] = new List<Token>();
}
postingsByDoc[docCount].Add(token);
tokens.Add(token);
pos += posIncr;
// stuff abs position into type:
token.Type = "" + pos;
offset += offIncr + tokenOffset;
//System.out.println(" " + token + " posIncr=" + token.getPositionIncrement() + " pos=" + pos + " off=" + token.StartOffset() + "/" + token.EndOffset() + " (freq=" + postingsByDoc.Get(docCount).Size() + ")");
}
doc.Add(new Field("content", new CannedTokenStream(tokens.ToArray()), ft));
w.AddDocument(doc);
}
DirectoryReader r = w.Reader;
w.Dispose();
string[] terms = new string[] { "a", "b", "c", "d" };
foreach (AtomicReaderContext ctx in r.Leaves)
{
// TODO: improve this
AtomicReader sub = (AtomicReader)ctx.Reader;
//System.out.println("\nsub=" + sub);
TermsEnum termsEnum = sub.Fields.Terms("content").Iterator(null);
DocsEnum docs = null;
DocsAndPositionsEnum docsAndPositions = null;
DocsAndPositionsEnum docsAndPositionsAndOffsets = null;
FieldCache.Ints docIDToID = FieldCache.DEFAULT.GetInts(sub, "id", false);
foreach (string term in terms)
{
//System.out.println(" term=" + term);
if (termsEnum.SeekExact(new BytesRef(term)))
{
docs = termsEnum.Docs(null, docs);
Assert.IsNotNull(docs);
int doc;
//System.out.println(" doc/freq");
while ((doc = docs.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
IList<Token> expected = actualTokens[term][docIDToID.Get(doc)];
//System.out.println(" doc=" + docIDToID.Get(doc) + " docID=" + doc + " " + expected.Size() + " freq");
Assert.IsNotNull(expected);
Assert.AreEqual(expected.Count, docs.Freq());
}
// explicitly exclude offsets here
docsAndPositions = termsEnum.DocsAndPositions(null, docsAndPositions, DocsAndPositionsEnum.FLAG_PAYLOADS);
Assert.IsNotNull(docsAndPositions);
//System.out.println(" doc/freq/pos");
while ((doc = docsAndPositions.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
IList<Token> expected = actualTokens[term][docIDToID.Get(doc)];
//System.out.println(" doc=" + docIDToID.Get(doc) + " " + expected.Size() + " freq");
Assert.IsNotNull(expected);
Assert.AreEqual(expected.Count, docsAndPositions.Freq());
foreach (Token token in expected)
{
int pos = Convert.ToInt32(token.Type);
//System.out.println(" pos=" + pos);
Assert.AreEqual(pos, docsAndPositions.NextPosition());
}
}
docsAndPositionsAndOffsets = termsEnum.DocsAndPositions(null, docsAndPositions);
Assert.IsNotNull(docsAndPositionsAndOffsets);
//System.out.println(" doc/freq/pos/offs");
while ((doc = docsAndPositionsAndOffsets.NextDoc()) != DocIdSetIterator.NO_MORE_DOCS)
{
IList<Token> expected = actualTokens[term][docIDToID.Get(doc)];
//System.out.println(" doc=" + docIDToID.Get(doc) + " " + expected.Size() + " freq");
Assert.IsNotNull(expected);
Assert.AreEqual(expected.Count, docsAndPositionsAndOffsets.Freq());
foreach (Token token in expected)
{
int pos = Convert.ToInt32(token.Type);
//System.out.println(" pos=" + pos);
Assert.AreEqual(pos, docsAndPositionsAndOffsets.NextPosition());
Assert.AreEqual(token.StartOffset(), docsAndPositionsAndOffsets.StartOffset());
Assert.AreEqual(token.EndOffset(), docsAndPositionsAndOffsets.EndOffset());
}
}
}
}
// TODO: test advance:
}
r.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestWithUnindexedFields()
{
Directory dir = NewDirectory();
RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, Iwc);
for (int i = 0; i < 100; i++)
{
Document doc = new Document();
// ensure at least one doc is indexed with offsets
if (i < 99 && Random().Next(2) == 0)
{
// stored only
FieldType ft = new FieldType();
ft.Indexed = false;
ft.Stored = true;
doc.Add(new Field("foo", "boo!", ft));
}
else
{
FieldType ft = new FieldType(TextField.TYPE_STORED);
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
if (Random().NextBoolean())
{
// store some term vectors for the checkindex cross-check
ft.StoreTermVectors = true;
ft.StoreTermVectorPositions = true;
ft.StoreTermVectorOffsets = true;
}
doc.Add(new Field("foo", "bar", ft));
}
riw.AddDocument(doc);
}
CompositeReader ir = riw.Reader;
AtomicReader slow = SlowCompositeReaderWrapper.Wrap(ir);
FieldInfos fis = slow.FieldInfos;
Assert.AreEqual(FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, fis.FieldInfo("foo").FieldIndexOptions);
slow.Dispose();
ir.Dispose();
riw.Dispose();
dir.Dispose();
}
[Test]
public virtual void TestAddFieldTwice()
{
Directory dir = NewDirectory();
RandomIndexWriter iw = new RandomIndexWriter(Random(), dir);
Document doc = new Document();
FieldType customType3 = new FieldType(TextField.TYPE_STORED);
customType3.StoreTermVectors = true;
customType3.StoreTermVectorPositions = true;
customType3.StoreTermVectorOffsets = true;
customType3.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
doc.Add(new Field("content3", "here is more content with aaa aaa aaa", customType3));
doc.Add(new Field("content3", "here is more content with aaa aaa aaa", customType3));
iw.AddDocument(doc);
iw.Dispose();
dir.Dispose(); // checkindex
}
// NOTE: the next two tests aren't that good as we need an EvilToken...
[Test]
public virtual void TestNegativeOffsets()
{
try
{
CheckTokens(new Token[] { MakeToken("foo", 1, -1, -1) });
Assert.Fail();
}
catch (System.ArgumentException expected)
{
//expected
}
}
[Test]
public virtual void TestIllegalOffsets()
{
try
{
CheckTokens(new Token[] { MakeToken("foo", 1, 1, 0) });
Assert.Fail();
}
catch (System.ArgumentException expected)
{
//expected
}
}
[Test]
public virtual void TestBackwardsOffsets()
{
try
{
CheckTokens(new Token[] { MakeToken("foo", 1, 0, 3), MakeToken("foo", 1, 4, 7), MakeToken("foo", 0, 3, 6) });
Assert.Fail();
}
catch (System.ArgumentException expected)
{
// expected
}
}
[Test]
public virtual void TestStackedTokens()
{
CheckTokens(new Token[] { MakeToken("foo", 1, 0, 3), MakeToken("foo", 0, 0, 3), MakeToken("foo", 0, 0, 3) });
}
[Test]
public virtual void TestLegalbutVeryLargeOffsets()
{
Directory dir = NewDirectory();
IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, null));
Document doc = new Document();
Token t1 = new Token("foo", 0, int.MaxValue - 500);
if (Random().NextBoolean())
{
t1.Payload = new BytesRef("test");
}
Token t2 = new Token("foo", int.MaxValue - 500, int.MaxValue);
TokenStream tokenStream = new CannedTokenStream(new Token[] { t1, t2 });
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
// store some term vectors for the checkindex cross-check
ft.StoreTermVectors = true;
ft.StoreTermVectorPositions = true;
ft.StoreTermVectorOffsets = true;
Field field = new Field("foo", tokenStream, ft);
doc.Add(field);
iw.AddDocument(doc);
iw.Dispose();
dir.Dispose();
}
// TODO: more tests with other possibilities
private void CheckTokens(Token[] tokens)
{
Directory dir = NewDirectory();
RandomIndexWriter riw = new RandomIndexWriter(Random(), dir, Iwc);
bool success = false;
try
{
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
// store some term vectors for the checkindex cross-check
ft.StoreTermVectors = true;
ft.StoreTermVectorPositions = true;
ft.StoreTermVectorOffsets = true;
Document doc = new Document();
doc.Add(new Field("body", new CannedTokenStream(tokens), ft));
riw.AddDocument(doc);
success = true;
}
finally
{
if (success)
{
IOUtils.Close(riw, dir);
}
else
{
IOUtils.CloseWhileHandlingException(riw, dir);
}
}
}
private Token MakeToken(string text, int posIncr, int startOffset, int endOffset)
{
Token t = new Token();
t.Append(text);
t.PositionIncrement = posIncr;
t.SetOffset(startOffset, endOffset);
return t;
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly IFormattingRule _lineAdjustmentFormattingRule;
private readonly IFormattingRule _endRegionFormattingRule;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
IFormattingRule lineAdjustmentFormattingRule,
IFormattingRule endRegionFormattingRule)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
{
return _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
}
protected int GetTabSize(SourceText text)
{
var snapshot = text.FindCorrespondingEditorTextSnapshot();
return GetTabSize(snapshot);
}
protected int GetTabSize(ITextSnapshot snapshot)
{
if (snapshot == null)
{
throw new ArgumentNullException("snapshot");
}
var textBuffer = snapshot.TextBuffer;
return _editorOptionsFactoryService.GetOptions(textBuffer).GetTabSize();
}
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
protected abstract IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree);
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
int ordinal;
if (!nameOrdinalMap.TryGetValue(name, out ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
{
return _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
}
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
SyntaxNodeKey nodeKey;
if (!nodeKeyMap.TryGetKey(node, out nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
SyntaxNode node;
if (!nodeKeyMap.TryGetValue(nodeKey, out node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxNode node);
protected abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
return (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
EnvDTE.CodeElement element;
if (TryGetElementFromSource(state, project, typeSymbol, out element))
{
return element;
}
EnvDTE.vsCMElement elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = CreateInternalCodeElement(state, fileCodeModel, parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = CreateInternalCodeParameter(state, fileCodeModel, parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
string name;
int ordinal;
GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode;
string name;
GetImportParentAndName(node, out parentNode, out name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = CreateInternalCodeElement(state, fileCodeModel, parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string name = GetParameterName(node);
var parent = CreateInternalCodeElement(state, fileCodeModel, parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
string name;
int ordinal;
GetOptionNameAndOrdinal(node.Parent, node, out name, out ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetInheritsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = CreateInternalCodeElement(state, fileCodeModel, parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode parentNode = node.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
string namespaceName;
int ordinal;
GetImplementsNamespaceAndOrdinal(parentNode, node, out namespaceName, out ordinal);
var parent = CreateInternalCodeElement(state, fileCodeModel, parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
SyntaxNode attributeNode;
int index;
GetAttributeArgumentParentAndIndex(node, out attributeNode, out index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullName(ISymbol symbol);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Solution solution)
{
// TODO: (tomescht) make this testable through unit tests.
// Right now we have to go through the project system to find all
// the outstanding CodeElements which might be affected by the
// rename. This is silly. This functionality should be moved down
// into the service layer.
var workspace = solution.Workspace as VisualStudioWorkspaceImpl;
if (workspace == null)
{
throw Exceptions.ThrowEFail();
}
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation();
foreach (var project in workspace.ProjectTracker.Projects)
{
nodeKeyValidation.AddProject(project);
}
var optionSet = workspace.Services.GetService<IOptionService>().GetOptions();
// Rename symbol.
var newSolution = Renamer.RenameSymbolAsync(solution, symbol, newName, optionSet).WaitAndGetResult(CancellationToken.None);
var changedDocuments = newSolution.GetChangedDocuments(solution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public VirtualTreePoint? GetStartPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetStartPoint(node, part);
}
public VirtualTreePoint? GetEndPoint(SyntaxNode node, EnvDTE.vsCMPart? part)
{
return _nodeLocator.GetEndPoint(node, part);
}
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource &&
project.GetCompilationAsync().Result.ContainsSyntaxTree(location.SourceTree))
{
var document = project.GetDocument(location.SourceTree);
var fcm = state.Workspace.GetFileCodeModel(document.Id);
if (fcm != null)
{
var fileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fcm);
element = fileCodeModel.CodeElementFromPosition(location.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
}
return false;
}
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
{
return GetParameterName(node);
}
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.InvalidAccess, "access");
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
{
return (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
}
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
{
// TODO(DustinCa): Verify this list against VB
switch (type)
{
case EnvDTE.vsCMTypeRef.vsCMTypeRefBool:
return SpecialType.System_Boolean;
case EnvDTE.vsCMTypeRef.vsCMTypeRefByte:
return SpecialType.System_Byte;
case EnvDTE.vsCMTypeRef.vsCMTypeRefChar:
return SpecialType.System_Char;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal:
return SpecialType.System_Decimal;
case EnvDTE.vsCMTypeRef.vsCMTypeRefDouble:
return SpecialType.System_Double;
case EnvDTE.vsCMTypeRef.vsCMTypeRefFloat:
return SpecialType.System_Single;
case EnvDTE.vsCMTypeRef.vsCMTypeRefInt:
return SpecialType.System_Int32;
case EnvDTE.vsCMTypeRef.vsCMTypeRefLong:
return SpecialType.System_Int64;
case EnvDTE.vsCMTypeRef.vsCMTypeRefObject:
return SpecialType.System_Object;
case EnvDTE.vsCMTypeRef.vsCMTypeRefShort:
return SpecialType.System_Int16;
case EnvDTE.vsCMTypeRef.vsCMTypeRefString:
return SpecialType.System_String;
case EnvDTE.vsCMTypeRef.vsCMTypeRefVoid:
return SpecialType.System_Void;
default:
// TODO: Support vsCMTypeRef2? It doesn't appear that Dev10 C# does...
throw new ArgumentException();
}
}
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
{
return compilation.GetSpecialType(GetSpecialType(type));
}
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string)
{
typeSymbol = GetTypeSymbolFromPartialName((string)type, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
GetMemberNodes);
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int)
{
result = (int)position;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string)
{
var name = (string)position;
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetFlattenedMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetFlattenedMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetAttributeInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetImportInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
private int GetParameterInsertionIndex(SyntaxNode container, int insertionIndex)
{
return insertionIndex;
}
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<IFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = node.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var newContainerNode = insertNodeIntoContainer(insertionIndex, annotatedNode, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = Simplifier.ReduceAsync(document, annotation, optionSet: null, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(containerNode, insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(containerNode, insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(containerNode, insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
{
return _eventCollector.Collect(oldTree, newTree);
}
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendents may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendents may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendents may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendents may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcav = Google.Cloud.ArtifactRegistry.V1Beta2;
using sys = System;
namespace Google.Cloud.ArtifactRegistry.V1Beta2
{
/// <summary>Resource name for the <c>Version</c> resource.</summary>
public sealed partial class VersionName : gax::IResourceName, sys::IEquatable<VersionName>
{
/// <summary>The possible contents of <see cref="VersionName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>
/// projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </summary>
ProjectLocationRepositoryPackageVersion = 1,
}
private static gax::PathTemplate s_projectLocationRepositoryPackageVersion = new gax::PathTemplate("projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}");
/// <summary>Creates a <see cref="VersionName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="VersionName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static VersionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new VersionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="VersionName"/> with the pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="packageId">The <c>Package</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="VersionName"/> constructed from the provided ids.</returns>
public static VersionName FromProjectLocationRepositoryPackageVersion(string projectId, string locationId, string repositoryId, string packageId, string versionId) =>
new VersionName(ResourceNameType.ProjectLocationRepositoryPackageVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), packageId: gax::GaxPreconditions.CheckNotNullOrEmpty(packageId, nameof(packageId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="packageId">The <c>Package</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </returns>
public static string Format(string projectId, string locationId, string repositoryId, string packageId, string versionId) =>
FormatProjectLocationRepositoryPackageVersion(projectId, locationId, repositoryId, packageId, versionId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="VersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="packageId">The <c>Package</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="VersionName"/> with pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// .
/// </returns>
public static string FormatProjectLocationRepositoryPackageVersion(string projectId, string locationId, string repositoryId, string packageId, string versionId) =>
s_projectLocationRepositoryPackageVersion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), gax::GaxPreconditions.CheckNotNullOrEmpty(packageId, nameof(packageId)), gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId)));
/// <summary>Parses the given resource name string into a new <see cref="VersionName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="VersionName"/> if successful.</returns>
public static VersionName Parse(string versionName) => Parse(versionName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="VersionName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="VersionName"/> if successful.</returns>
public static VersionName Parse(string versionName, bool allowUnparsed) =>
TryParse(versionName, allowUnparsed, out VersionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string versionName, out VersionName result) => TryParse(versionName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="VersionName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="versionName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="VersionName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string versionName, bool allowUnparsed, out VersionName result)
{
gax::GaxPreconditions.CheckNotNull(versionName, nameof(versionName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationRepositoryPackageVersion.TryParseName(versionName, out resourceName))
{
result = FromProjectLocationRepositoryPackageVersion(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(versionName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private VersionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string packageId = null, string projectId = null, string repositoryId = null, string versionId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
LocationId = locationId;
PackageId = packageId;
ProjectId = projectId;
RepositoryId = repositoryId;
VersionId = versionId;
}
/// <summary>
/// Constructs a new instance of a <see cref="VersionName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/repositories/{repository}/packages/{package}/versions/{version}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="repositoryId">The <c>Repository</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="packageId">The <c>Package</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="versionId">The <c>Version</c> ID. Must not be <c>null</c> or empty.</param>
public VersionName(string projectId, string locationId, string repositoryId, string packageId, string versionId) : this(ResourceNameType.ProjectLocationRepositoryPackageVersion, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), repositoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(repositoryId, nameof(repositoryId)), packageId: gax::GaxPreconditions.CheckNotNullOrEmpty(packageId, nameof(packageId)), versionId: gax::GaxPreconditions.CheckNotNullOrEmpty(versionId, nameof(versionId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Package</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string PackageId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Repository</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string RepositoryId { get; }
/// <summary>
/// The <c>Version</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string VersionId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationRepositoryPackageVersion: return s_projectLocationRepositoryPackageVersion.Expand(ProjectId, LocationId, RepositoryId, PackageId, VersionId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as VersionName);
/// <inheritdoc/>
public bool Equals(VersionName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(VersionName a, VersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(VersionName a, VersionName b) => !(a == b);
}
public partial class Version
{
/// <summary>
/// <see cref="gcav::VersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::VersionName VersionName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::VersionName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Xml.Serialization;
using Xsd2Code.Library;
using Xsd2Code.Library.Helpers;
using Xsd2Code.Properties;
namespace Xsd2Code
{
/// <summary>
/// Entry point class
/// </summary>
/// <remarks>
/// Revision history:
///
/// Modified 2009-02-20 by Ruslan Urban
/// Changed parsing of command-line arguments
///
/// Modified 2009-03-12 By Ruslan Urban
/// Enabled GenerateDataContracts option
///
/// </remarks>
internal class EntryPoint
{
[STAThread]
private static void Main(string[] args)
{
DisplayApplicationInfo();
// Display help when no parameters have been specified
if (args.Length < 1)
{
DisplayHelp();
return;
}
// Process command-line parameter switches for help and license
for (int i = 0; i < args.Length; i++)
{
switch (args[i].Trim().ToLower())
{
case "/lic":
case "/license":
DisplayLicense();
return;
case "/?":
case "/h":
case "/hlp":
case "/help":
DisplayHelp();
return;
default:
break;
}
}
// Create new instance of GeneratorParams, which contains all generation parameters
var xsdFilePath = args[0];
var generatorParams = new GeneratorParams { InputFilePath = xsdFilePath };
// When only the XSD file name is specified,
// try to locate generated Designer file and load output parameters from the file header
if (args.Length == 1)
{
string outputFilePath;
var tempGeneratorParams = GeneratorParams.LoadFromFile(xsdFilePath, out outputFilePath);
if (tempGeneratorParams != null)
{
generatorParams = tempGeneratorParams;
generatorParams.InputFilePath = xsdFilePath;
if (!string.IsNullOrEmpty(outputFilePath))
generatorParams.OutputFilePath = outputFilePath;
}
}
// Second command-line parameter that is not a switch is the generated code namespace
if (args.Length > 1 && !args[1].StartsWith("/"))
{
generatorParams.NameSpace = args[1];
// Third command-line parameter that is not a switch is the generated code namespace
if (args.Length > 2 && !args[2].StartsWith("/"))
generatorParams.OutputFilePath = args[2];
}
// Process command-line parameter switches
for (int i = 1; i < args.Length; i++)
{
switch (args[i].Trim().ToLower())
{
case "/n":
case "/ns":
case "/namespace":
if (i < args.Length - 1)
{
generatorParams.NameSpace = args[i + 1];
i++;
}
break;
case "/o":
case "/out":
case "/output":
if (i < args.Length - 1)
{
generatorParams.OutputFilePath = args[i + 1];
i++;
}
break;
case "/l":
case "/lang":
case "/language":
if (i < args.Length - 1)
{
generatorParams.Language = Utility.GetGenerationLanguage(args[i + 1]);
i++;
}
break;
case "/c":
case "/col":
case "/collection":
case "/collectionbase":
if (i < args.Length - 1)
{
generatorParams.CollectionObjectType = Utility.ToEnum<CollectionType>(args[i + 1]);
i++;
}
break;
//Duplicate with /pl
case "/cb":
case "/codebase":
if (i < args.Length - 1)
{
Console.WriteLine("Warning: /cb /codebase is obsolete please use /pl[atform] <Platform> - Generated code target platform (Net20|Net30|Net35|Silverlight20). Default: Net20");
generatorParams.TargetFramework = Utility.ToEnum<TargetFramework>(args[i + 1]);
i++;
}
break;
case "/gsf":
case "/generateseparatefiles":
if (i < args.Length - 1)
{
generatorParams.GenerateSeparateFiles = true;
}
break;
case "/cu":
case "/customusings":
if (i < args.Length - 1)
{
//generatorParams.CustomUsingsString = args[i + 1];
foreach (string item in args[i + 1].Split(','))
{
generatorParams.CustomUsings.Add(new NamespaceParam { NameSpace = item });
}
i++;
}
break;
case "/lf":
case "/lfm":
if (i < args.Length - 1)
{
generatorParams.Serialization.LoadFromFileMethodName = args[i + 1];
i++;
}
break;
case "/sm":
if (i < args.Length - 1)
{
generatorParams.Serialization.SerializeMethodName = args[i + 1];
i++;
}
break;
case "/sf":
case "/sfm":
if (i < args.Length - 1)
{
generatorParams.Serialization.SaveToFileMethodName = args[i + 1];
i++;
}
break;
case "/p":
case "/pl":
case "/tp":
case "/tpl":
case "/platform":
if (i < args.Length - 1)
{
generatorParams.TargetFramework = Utility.GetTargetPlatform(args[i + 1]);
i++;
}
break;
case "/u":
case "/us":
case "/using":
if (i < args.Length - 1)
{
var nsList = args[i + 1].Split(',');
foreach (var ns in nsList)
generatorParams.CustomUsings.Add(new NamespaceParam { NameSpace = ns });
i++;
}
break;
case "/dbg":
case "/dbg+":
case "/debug":
case "/debug+":
generatorParams.Miscellaneous.DisableDebug = false;
break;
case "/dbg-":
case "/debug-":
generatorParams.Miscellaneous.DisableDebug = true;
break;
case "/db":
case "/db+":
generatorParams.EnableDataBinding = true;
break;
case "/db-":
generatorParams.EnableDataBinding = false;
break;
case "/dc":
case "/dc+":
generatorParams.GenerateDataContracts = true;
break;
case "/dc-":
generatorParams.GenerateDataContracts = false;
break;
case "/ap":
case "/ap+":
generatorParams.PropertyParams.AutomaticProperties = true;
break;
case "/ap-":
generatorParams.PropertyParams.AutomaticProperties = false;
break;
case "/if":
case "/if+":
generatorParams.EnableInitializeFields = true;
break;
case "/if-":
generatorParams.EnableInitializeFields = false;
break;
case "/eit":
case "/eit+":
generatorParams.Miscellaneous.ExcludeIncludedTypes = true;
break;
case "/eit-":
generatorParams.Miscellaneous.ExcludeIncludedTypes = false;
break;
case "/gbc":
case "/gbc+":
generatorParams.GenericBaseClass.Enabled = true;
break;
case "/gbc-":
generatorParams.GenericBaseClass.Enabled = false;
break;
case "/ggbc":
case "/ggbc+":
generatorParams.GenericBaseClass.GenerateBaseClass = true;
break;
case "/ggbc-":
generatorParams.GenericBaseClass.GenerateBaseClass = false;
break;
case "/sc":
case "/sc+":
generatorParams.Miscellaneous.EnableSummaryComment = true;
break;
case "/sc-":
case "/sum-":
generatorParams.Miscellaneous.EnableSummaryComment = false;
break;
case "/xa":
case "/xa+":
generatorParams.Serialization.GenerateXmlAttributes = true;
break;
case "/xa-":
generatorParams.Serialization.GenerateXmlAttributes = false;
break;
case "/cl":
case "/cl+":
generatorParams.GenerateCloneMethod = true;
break;
case "/cl-":
generatorParams.GenerateCloneMethod = false;
break;
case "/hp":
case "/hp+":
generatorParams.Miscellaneous.HidePrivateFieldInIde = true;
break;
case "/hp-":
generatorParams.Miscellaneous.HidePrivateFieldInIde = false;
break;
case "/tc":
case "/tc+":
generatorParams.TrackingChanges.Enabled = true;
break;
case "/tc-":
generatorParams.TrackingChanges.Enabled = false;
break;
case "/tcc":
case "/tcc+":
generatorParams.TrackingChanges.GenerateTrackingClasses = true;
break;
case "/tcc-":
generatorParams.TrackingChanges.GenerateTrackingClasses = false;
break;
case "/ssp":
case "/ssp+":
generatorParams.PropertyParams.GenerateShouldSerializeProperty = true;
break;
case "/ssp-":
generatorParams.PropertyParams.GenerateShouldSerializeProperty = false;
break;
case "/s":
case "/s+":
case "/is":
case "/is+":
generatorParams.Serialization.Enabled = true;
break;
case "/s-":
case "/is-":
generatorParams.Serialization.Enabled = false;
break;
case "/ee":
case "/ee+":
generatorParams.Serialization.EnableEncoding = true;
break;
case "/ee-":
generatorParams.Serialization.EnableEncoding = false;
break;
case "/co":
case "/codeoptions":
if (i < args.Length - 1)
{
generatorParams.CodeGenerationOptions = (CodeGenerationOptions)Convert.ToInt32(args[i + 1]);
i++;
}
break;
}
}
// Auto-generate missing output file path
if (string.IsNullOrEmpty(generatorParams.OutputFilePath))
{
generatorParams.OutputFilePath =
Utility.GetOutputFilePath(generatorParams.InputFilePath,
generatorParams.Language);
}
// Auto-generate missing generated code namespace
if (string.IsNullOrEmpty(generatorParams.NameSpace))
generatorParams.NameSpace = Path.GetFileNameWithoutExtension(generatorParams.InputFilePath);
// Create an instance of Generator
var generator = new GeneratorFacade(generatorParams);
// Generate code
var result = generator.Generate();
if (!result.Success)
{
// Display the error and wait for user confirmation
Console.WriteLine();
Console.WriteLine(result.Messages.ToString());
Console.WriteLine();
Console.WriteLine("Press ENTER to continue...");
Console.ReadLine();
return;
}
Console.WriteLine("Generated code has been saved into the file {0}.", result.Entity);
Console.WriteLine();
Console.WriteLine("Finished");
Console.WriteLine();
}
private static void DisplayApplicationInfo()
{
var currentAssembly = Assembly.GetExecutingAssembly();
var currentAssemblyName = currentAssembly.GetName();
Console.WriteLine();
Console.WriteLine("Open Xsd2Code Version {0}", currentAssemblyName.Version);
Console.WriteLine("Code generation utility from XML schema files.");
Console.WriteLine();
}
/// <summary>
/// Display contents of the help file ~/Resources/Help.txt
/// </summary>
private static void DisplayHelp()
{
Console.WriteLine();
Console.WriteLine(Resources.Help);
Console.WriteLine();
}
/// <summary>
/// Display contents of the help file ~/Resources/Help.txt
/// </summary>
private static void DisplayLicense()
{
Console.WriteLine();
Console.WriteLine(Resources.License);
Console.WriteLine();
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using QUnit;
#pragma warning disable 184, 458, 1720
namespace CoreLib.TestScript.Reflection {
[TestFixture]
public class TypeSystemLanguageSupportTests {
public class C1 {}
[IncludeGenericArguments]
public class C2<T> {}
public interface I1 {}
[IncludeGenericArguments]
public interface I2<T1> {}
public interface I3 : I1 {}
public interface I4 {}
[IncludeGenericArguments]
public interface I5<T1> : I2<T1> {}
[IncludeGenericArguments]
public interface I6<out T> {}
[IncludeGenericArguments]
public interface I7<in T> {}
[IncludeGenericArguments]
public interface I8<out T1, in T2> : I6<T1>, I7<T2> {}
[IncludeGenericArguments]
public interface I9<T1, out T2> {}
[IncludeGenericArguments]
public interface I10<out T1, in T2> : I8<T1,T2> {}
public class D1 : C1, I1 { }
[IncludeGenericArguments]
public class D2<T> : C2<T>, I2<T>, I1 {
}
public class D3 : C2<int>, I2<string> {
}
public class D4 : I3, I4 {
}
public class X1 : I1 {
}
public class X2 : X1 {
}
[IncludeGenericArguments]
public class Y1<T> : I6<T> {}
public class Y1X1 : Y1<X1> {}
public class Y1X2 : Y1<X2> {}
[IncludeGenericArguments]
public class Y2<T> : I7<T> {}
public class Y2X1 : Y2<X1> {}
public class Y2X2 : Y2<X2> {}
[IncludeGenericArguments]
public class Y3<T1, T2> : I8<T1, T2> {}
public class Y3X1X1 : Y3<X1, X1> {}
public class Y3X1X2 : Y3<X1, X2> {}
public class Y3X2X1 : Y3<X2, X1> {}
public class Y3X2X2 : Y3<X2, X2> {}
[IncludeGenericArguments]
public class Y4<T1, T2> : I9<T1, T2> {}
public class Y5<T1, T2> : I6<I8<T1, T2>> {}
public class Y6<T1, T2> : I7<I8<T1, T2>> {}
public enum E1 {}
public enum E2 {}
[Serializable]
public class BS {
public int X;
public BS(int x) {
X = x;
}
}
[Serializable(TypeCheckCode = "{$System.Script}.isValue({this}.y)")]
public class DS : BS {
public DS() : base(0) {}
}
[Imported(TypeCheckCode = "{$System.Script}.isValue({this}.y)")]
public class CI {
}
[IncludeGenericArguments]
private static bool CanConvert<T>(object arg) {
try {
#pragma warning disable 219 // The variable `x' is assigned but its value is never used
var x = (T)arg;
#pragma warning restore 219
return true;
}
catch {
return false;
}
}
[Test]
public void TypeIsWorksForReferenceTypes() {
Assert.IsFalse((object)new object() is C1, "#1");
Assert.IsTrue ((object)new C1() is object, "#2");
Assert.IsFalse((object)new object() is I1, "#3");
Assert.IsFalse((object)new C1() is D1, "#4");
Assert.IsTrue ((object)new D1() is C1, "#5");
Assert.IsTrue ((object)new D1() is I1, "#6");
Assert.IsTrue ((object)new D2<int>() is C2<int>, "#7");
Assert.IsFalse((object)new D2<int>() is C2<string>, "#8");
Assert.IsTrue ((object)new D2<int>() is I2<int>, "#9");
Assert.IsFalse((object)new D2<int>() is I2<string>, "#10");
Assert.IsTrue ((object)new D2<int>() is I1, "#11");
Assert.IsFalse((object)new D3() is C2<string>, "#12");
Assert.IsTrue ((object)new D3() is C2<int>, "#13");
Assert.IsFalse((object)new D3() is I2<int>, "#14");
Assert.IsTrue ((object)new D3() is I2<string>, "#15");
Assert.IsTrue ((object)new D4() is I1, "#16");
Assert.IsTrue ((object)new D4() is I3, "#17");
Assert.IsTrue ((object)new D4() is I4, "#18");
Assert.IsTrue ((object)new X2() is I1, "#19");
Assert.IsTrue ((object)new E2() is E1, "#20");
Assert.IsTrue ((object)new E1() is int, "#21");
Assert.IsTrue ((object)new E1() is object, "#22");
Assert.IsFalse((object)new Y1<X1>() is I7<X1>, "#23");
Assert.IsTrue ((object)new Y1<X1>() is I6<X1>, "#24");
Assert.IsTrue ((object)new Y1X1() is I6<X1>, "#25");
Assert.IsFalse((object)new Y1<X1>() is I6<X2>, "#26");
Assert.IsFalse((object)new Y1X1() is I6<X2>, "#27");
Assert.IsTrue ((object)new Y1<X2>() is I6<X1>, "#28");
Assert.IsTrue ((object)new Y1X2() is I6<X1>, "#29");
Assert.IsTrue ((object)new Y1<X2>() is I6<X2>, "#30");
Assert.IsTrue ((object)new Y1X2() is I6<X2>, "#31");
Assert.IsFalse((object)new Y2<X1>() is I6<X1>, "#32");
Assert.IsTrue ((object)new Y2<X1>() is I7<X1>, "#33");
Assert.IsTrue ((object)new Y2X1() is I7<X1>, "#34");
Assert.IsTrue ((object)new Y2<X1>() is I7<X2>, "#35");
Assert.IsTrue ((object)new Y2X1() is I7<X2>, "#36");
Assert.IsFalse((object)new Y2<X2>() is I7<X1>, "#37");
Assert.IsFalse((object)new Y2X2() is I7<X1>, "#38");
Assert.IsTrue ((object)new Y2<X2>() is I7<X2>, "#39");
Assert.IsTrue ((object)new Y2X2() is I7<X2>, "#40");
Assert.IsFalse((object)new Y3<X1, X1>() is I1, "#41");
Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X1>, "#42");
Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X1>, "#43");
Assert.IsFalse((object)new Y3<X1, X2>() is I8<X1, X1>, "#44");
Assert.IsFalse((object)new Y3X1X2() is I8<X1, X1>, "#45");
Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X1>, "#46");
Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X1>, "#47");
Assert.IsFalse((object)new Y3<X2, X2>() is I8<X1, X1>, "#48");
Assert.IsFalse((object)new Y3X2X2() is I8<X1, X1>, "#49");
Assert.IsTrue ((object)new Y3<X1, X1>() is I8<X1, X2>, "#50");
Assert.IsTrue ((object)new Y3X1X1() is I8<X1, X2>, "#51");
Assert.IsTrue ((object)new Y3<X1, X2>() is I8<X1, X2>, "#52");
Assert.IsTrue ((object)new Y3X1X2() is I8<X1, X2>, "#53");
Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X1, X2>, "#54");
Assert.IsTrue ((object)new Y3X2X1() is I8<X1, X2>, "#55");
Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X1, X2>, "#56");
Assert.IsTrue ((object)new Y3X2X2() is I8<X1, X2>, "#57");
Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X1>, "#58");
Assert.IsFalse((object)new Y3X1X1() is I8<X2, X1>, "#59");
Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X1>, "#60");
Assert.IsFalse((object)new Y3X1X2() is I8<X2, X1>, "#61");
Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X1>, "#62");
Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X1>, "#63");
Assert.IsFalse((object)new Y3<X2, X2>() is I8<X2, X1>, "#64");
Assert.IsFalse((object)new Y3X2X2() is I8<X2, X1>, "#65");
Assert.IsFalse((object)new Y3<X1, X1>() is I8<X2, X2>, "#66");
Assert.IsFalse((object)new Y3X1X1() is I8<X2, X2>, "#67");
Assert.IsFalse((object)new Y3<X1, X2>() is I8<X2, X2>, "#68");
Assert.IsFalse((object)new Y3X1X2() is I8<X2, X2>, "#69");
Assert.IsTrue ((object)new Y3<X2, X1>() is I8<X2, X2>, "#70");
Assert.IsTrue ((object)new Y3X2X1() is I8<X2, X2>, "#71");
Assert.IsTrue ((object)new Y3<X2, X2>() is I8<X2, X2>, "#72");
Assert.IsTrue ((object)new Y3X2X2() is I8<X2, X2>, "#73");
Assert.IsTrue ((object)new Y4<string, X1>() is I9<string, X1>, "#74");
Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X1>, "#75");
Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X1>, "#76");
Assert.IsTrue ((object)new Y4<object, X1>() is I9<object, X1>, "#77");
Assert.IsFalse((object)new Y4<string, X1>() is I9<string, X2>, "#78");
Assert.IsFalse((object)new Y4<string, X1>() is I9<object, X2>, "#79");
Assert.IsFalse((object)new Y4<object, X1>() is I9<string, X2>, "#80");
Assert.IsFalse((object)new Y4<object, X1>() is I9<object, X2>, "#81");
Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X1>, "#82");
Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X1>, "#83");
Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X1>, "#84");
Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X1>, "#85");
Assert.IsTrue ((object)new Y4<string, X2>() is I9<string, X2>, "#86");
Assert.IsFalse((object)new Y4<string, X2>() is I9<object, X2>, "#87");
Assert.IsFalse((object)new Y4<object, X2>() is I9<string, X2>, "#88");
Assert.IsTrue ((object)new Y4<object, X2>() is I9<object, X2>, "#89");
Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I6<X1>>, "#90");
Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X1>>, "#91");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I6<X2>>, "#92");
Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I7<X2>>, "#93");
Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X1>>, "#94");
Assert.IsTrue ((object)new Y5<X1, X1>() is I6<I8<X1, X2>>, "#95");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X1>>, "#96");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I8<X2, X2>>, "#97");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X1>>, "#98");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X1, X2>>, "#99");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X1>>, "#100");
Assert.IsFalse((object)new Y5<X1, X1>() is I6<I10<X2, X2>>, "#101");
Assert.IsTrue((object)new Y5<X2, X2>() is I6<I6<X1>>, "#102");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I7<X1>>, "#103");
Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I6<X2>>, "#104");
Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I7<X2>>, "#105");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X1, X1>>, "#106");
Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X1, X2>>, "#107");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I8<X2, X1>>, "#108");
Assert.IsTrue ((object)new Y5<X2, X2>() is I6<I8<X2, X2>>, "#109");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X1>>, "#110");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X1, X2>>, "#111");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X1>>, "#112");
Assert.IsFalse((object)new Y5<X2, X2>() is I6<I10<X2, X2>>, "#113");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X1>>, "#114");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X1>>, "#115");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I6<X2>>, "#116");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I7<X2>>, "#117");
Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X1, X1>>, "#118");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X1, X2>>, "#119");
Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I8<X2, X1>>, "#120");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I8<X2, X2>>, "#121");
Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X1, X1>>, "#122");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X1, X2>>, "#123");
Assert.IsTrue ((object)new Y6<X1, X1>() is I7<I10<X2, X1>>, "#124");
Assert.IsFalse((object)new Y6<X1, X1>() is I7<I10<X2, X2>>, "#125");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X1>>, "#126");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X1>>, "#127");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I6<X2>>, "#128");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I7<X2>>, "#129");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X1>>, "#130");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I8<X1, X2>>, "#131");
Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X1>>, "#132");
Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I8<X2, X2>>, "#133");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X1>>, "#134");
Assert.IsFalse((object)new Y6<X2, X2>() is I7<I10<X1, X2>>, "#135");
Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X1>>, "#136");
Assert.IsTrue ((object)new Y6<X2, X2>() is I7<I10<X2, X2>>, "#137");
Assert.IsFalse((object)null is object, "#138");
}
[Test]
public void TypeAsWorksForReferenceTypes() {
Assert.IsFalse(((object)new object() as C1) != null, "#1");
Assert.IsTrue (((object)new C1() as object) != null, "#2");
Assert.IsFalse(((object)new object() as I1) != null, "#3");
Assert.IsFalse(((object)new C1() as D1) != null, "#4");
Assert.IsTrue (((object)new D1() as C1) != null, "#5");
Assert.IsTrue (((object)new D1() as I1) != null, "#6");
Assert.IsTrue (((object)new D2<int>() as C2<int>) != null, "#7");
Assert.IsFalse(((object)new D2<int>() as C2<string>) != null, "#8");
Assert.IsTrue (((object)new D2<int>() as I2<int>) != null, "#9");
Assert.IsFalse(((object)new D2<int>() as I2<string>) != null, "#10");
Assert.IsTrue (((object)new D2<int>() as I1) != null, "#11");
Assert.IsFalse(((object)new D3() as C2<string>) != null, "#12");
Assert.IsTrue (((object)new D3() as C2<int>) != null, "#13");
Assert.IsFalse(((object)new D3() as I2<int>) != null, "#14");
Assert.IsTrue (((object)new D3() as I2<string>) != null, "#15");
Assert.IsTrue (((object)new D4() as I1) != null, "#16");
Assert.IsTrue (((object)new D4() as I3) != null, "#17");
Assert.IsTrue (((object)new D4() as I4) != null, "#18");
Assert.IsTrue (((object)new X2() as I1) != null, "#19");
Assert.IsTrue (((object)new E2() as E1?) != null, "#20");
Assert.IsTrue (((object)new E1() as int?) != null, "#21");
Assert.IsTrue (((object)new E1() as object) != null, "#22");
Assert.IsFalse(((object)new Y1<X1>() as I7<X1>) != null, "#23");
Assert.IsTrue (((object)new Y1<X1>() as I6<X1>) != null, "#24");
Assert.IsTrue (((object)new Y1X1() as I6<X1>) != null, "#25");
Assert.IsFalse(((object)new Y1<X1>() as I6<X2>) != null, "#26");
Assert.IsFalse(((object)new Y1X1() as I6<X2>) != null, "#27");
Assert.IsTrue (((object)new Y1<X2>() as I6<X1>) != null, "#28");
Assert.IsTrue (((object)new Y1X2() as I6<X1>) != null, "#29");
Assert.IsTrue (((object)new Y1<X2>() as I6<X2>) != null, "#30");
Assert.IsTrue (((object)new Y1X2() as I6<X2>) != null, "#31");
Assert.IsFalse(((object)new Y2<X1>() as I6<X1>) != null, "#32");
Assert.IsTrue (((object)new Y2<X1>() as I7<X1>) != null, "#33");
Assert.IsTrue (((object)new Y2X1() as I7<X1>) != null, "#34");
Assert.IsTrue (((object)new Y2<X1>() as I7<X2>) != null, "#35");
Assert.IsTrue (((object)new Y2X1() as I7<X2>) != null, "#36");
Assert.IsFalse(((object)new Y2<X2>() as I7<X1>) != null, "#37");
Assert.IsFalse(((object)new Y2X2() as I7<X1>) != null, "#38");
Assert.IsTrue (((object)new Y2<X2>() as I7<X2>) != null, "#39");
Assert.IsTrue (((object)new Y2X2() as I7<X2>) != null, "#40");
Assert.IsFalse(((object)new Y3<X1, X1>() as I1) != null, "#41");
Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X1>) != null, "#42");
Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X1>) != null, "#43");
Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X1, X1>) != null, "#44");
Assert.IsFalse(((object)new Y3X1X2() as I8<X1, X1>) != null, "#45");
Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X1>) != null, "#46");
Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X1>) != null, "#47");
Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X1, X1>) != null, "#48");
Assert.IsFalse(((object)new Y3X2X2() as I8<X1, X1>) != null, "#49");
Assert.IsTrue (((object)new Y3<X1, X1>() as I8<X1, X2>) != null, "#50");
Assert.IsTrue (((object)new Y3X1X1() as I8<X1, X2>) != null, "#51");
Assert.IsTrue (((object)new Y3<X1, X2>() as I8<X1, X2>) != null, "#52");
Assert.IsTrue (((object)new Y3X1X2() as I8<X1, X2>) != null, "#53");
Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X1, X2>) != null, "#54");
Assert.IsTrue (((object)new Y3X2X1() as I8<X1, X2>) != null, "#55");
Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X1, X2>) != null, "#56");
Assert.IsTrue (((object)new Y3X2X2() as I8<X1, X2>) != null, "#57");
Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X1>) != null, "#58");
Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X1>) != null, "#59");
Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X1>) != null, "#60");
Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X1>) != null, "#61");
Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X1>) != null, "#62");
Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X1>) != null, "#63");
Assert.IsFalse(((object)new Y3<X2, X2>() as I8<X2, X1>) != null, "#64");
Assert.IsFalse(((object)new Y3X2X2() as I8<X2, X1>) != null, "#65");
Assert.IsFalse(((object)new Y3<X1, X1>() as I8<X2, X2>) != null, "#66");
Assert.IsFalse(((object)new Y3X1X1() as I8<X2, X2>) != null, "#67");
Assert.IsFalse(((object)new Y3<X1, X2>() as I8<X2, X2>) != null, "#68");
Assert.IsFalse(((object)new Y3X1X2() as I8<X2, X2>) != null, "#69");
Assert.IsTrue (((object)new Y3<X2, X1>() as I8<X2, X2>) != null, "#70");
Assert.IsTrue (((object)new Y3X2X1() as I8<X2, X2>) != null, "#71");
Assert.IsTrue (((object)new Y3<X2, X2>() as I8<X2, X2>) != null, "#72");
Assert.IsTrue (((object)new Y3X2X2() as I8<X2, X2>) != null, "#73");
Assert.IsTrue (((object)new Y4<string, X1>() as I9<string, X1>) != null, "#74");
Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X1>) != null, "#75");
Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X1>) != null, "#76");
Assert.IsTrue (((object)new Y4<object, X1>() as I9<object, X1>) != null, "#77");
Assert.IsFalse(((object)new Y4<string, X1>() as I9<string, X2>) != null, "#78");
Assert.IsFalse(((object)new Y4<string, X1>() as I9<object, X2>) != null, "#79");
Assert.IsFalse(((object)new Y4<object, X1>() as I9<string, X2>) != null, "#80");
Assert.IsFalse(((object)new Y4<object, X1>() as I9<object, X2>) != null, "#81");
Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X1>) != null, "#82");
Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X1>) != null, "#83");
Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X1>) != null, "#84");
Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X1>) != null, "#85");
Assert.IsTrue (((object)new Y4<string, X2>() as I9<string, X2>) != null, "#86");
Assert.IsFalse(((object)new Y4<string, X2>() as I9<object, X2>) != null, "#87");
Assert.IsFalse(((object)new Y4<object, X2>() as I9<string, X2>) != null, "#88");
Assert.IsTrue (((object)new Y4<object, X2>() as I9<object, X2>) != null, "#89");
Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I6<X1>>) != null, "#90");
Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X1>>) != null, "#91");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I6<X2>>) != null, "#92");
Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I7<X2>>) != null, "#93");
Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X1>>) != null, "#94");
Assert.IsTrue (((object)new Y5<X1, X1>() as I6<I8<X1, X2>>) != null, "#95");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X1>>) != null, "#96");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I8<X2, X2>>) != null, "#97");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X1>>) != null, "#98");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X1, X2>>) != null, "#99");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X1>>) != null, "#100");
Assert.IsFalse(((object)new Y5<X1, X1>() as I6<I10<X2, X2>>) != null, "#101");
Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X1>>) != null, "#102");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I7<X1>>) != null, "#103");
Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I6<X2>>) != null, "#104");
Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I7<X2>>) != null, "#105");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X1, X1>>) != null, "#106");
Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X1, X2>>) != null, "#107");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I8<X2, X1>>) != null, "#108");
Assert.IsTrue (((object)new Y5<X2, X2>() as I6<I8<X2, X2>>) != null, "#109");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X1>>) != null, "#110");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X1, X2>>) != null, "#111");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X1>>) != null, "#112");
Assert.IsFalse(((object)new Y5<X2, X2>() as I6<I10<X2, X2>>) != null, "#113");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X1>>) != null, "#114");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X1>>) != null, "#115");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I6<X2>>) != null, "#116");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I7<X2>>) != null, "#117");
Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X1, X1>>) != null, "#118");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X1, X2>>) != null, "#119");
Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I8<X2, X1>>) != null, "#120");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I8<X2, X2>>) != null, "#121");
Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X1, X1>>) != null, "#122");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X1, X2>>) != null, "#123");
Assert.IsTrue (((object)new Y6<X1, X1>() as I7<I10<X2, X1>>) != null, "#124");
Assert.IsFalse(((object)new Y6<X1, X1>() as I7<I10<X2, X2>>) != null, "#125");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X1>>) != null, "#126");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X1>>) != null, "#127");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I6<X2>>) != null, "#128");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I7<X2>>) != null, "#129");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X1>>) != null, "#130");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I8<X1, X2>>) != null, "#131");
Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X1>>) != null, "#132");
Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I8<X2, X2>>) != null, "#133");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X1>>) != null, "#134");
Assert.IsFalse(((object)new Y6<X2, X2>() as I7<I10<X1, X2>>) != null, "#135");
Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X1>>) != null, "#136");
Assert.IsTrue (((object)new Y6<X2, X2>() as I7<I10<X2, X2>>) != null, "#137");
Assert.IsFalse(((object)null as object) != null, "#138");
}
[Test]
public void CastWorksForReferenceTypes() {
Assert.IsFalse(CanConvert<C1>(new object()), "#1");
Assert.IsTrue (CanConvert<object>(new C1()), "#2");
Assert.IsFalse(CanConvert<I1>(new object()), "#3");
Assert.IsFalse(CanConvert<D1>(new C1()), "#4");
Assert.IsTrue (CanConvert<C1>(new D1()), "#5");
Assert.IsTrue (CanConvert<I1>(new D1()), "#6");
Assert.IsTrue (CanConvert<C2<int>>(new D2<int>()), "#7");
Assert.IsFalse(CanConvert<C2<string>>(new D2<int>()), "#8");
Assert.IsTrue (CanConvert<I2<int>>(new D2<int>()), "#9");
Assert.IsFalse(CanConvert<I2<string>>(new D2<int>()), "#10");
Assert.IsTrue (CanConvert<I1>(new D2<int>()), "#11");
Assert.IsFalse(CanConvert<C2<string>>(new D3()), "#12");
Assert.IsTrue (CanConvert<C2<int>>(new D3()), "#13");
Assert.IsFalse(CanConvert<I2<int>>(new D3()), "#14");
Assert.IsTrue (CanConvert<I2<string>>(new D3()), "#15");
Assert.IsTrue (CanConvert<I1>(new D4()), "#16");
Assert.IsTrue (CanConvert<I3>(new D4()), "#17");
Assert.IsTrue (CanConvert<I4>(new D4()), "#18");
Assert.IsTrue (CanConvert<I1>(new X2()), "#19");
Assert.IsTrue (CanConvert<E1>(new E2()), "#20");
Assert.IsTrue (CanConvert<int>(new E1()), "#21");
Assert.IsTrue (CanConvert<object>(new E1()), "#22");
Assert.IsFalse(CanConvert<I7<X1>>(new Y1<X1>()), "#23");
Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X1>()), "#24");
Assert.IsTrue (CanConvert<I6<X1>>(new Y1X1()), "#25");
Assert.IsFalse(CanConvert<I6<X2>>(new Y1<X1>()), "#26");
Assert.IsFalse(CanConvert<I6<X2>>(new Y1X1()), "#27");
Assert.IsTrue (CanConvert<I6<X1>>(new Y1<X2>()), "#28");
Assert.IsTrue (CanConvert<I6<X1>>(new Y1X2()), "#29");
Assert.IsTrue (CanConvert<I6<X2>>(new Y1<X2>()), "#30");
Assert.IsTrue (CanConvert<I6<X2>>(new Y1X2()), "#31");
Assert.IsFalse(CanConvert<I6<X1>>(new Y2<X1>()), "#32");
Assert.IsTrue (CanConvert<I7<X1>>(new Y2<X1>()), "#33");
Assert.IsTrue (CanConvert<I7<X1>>(new Y2X1()), "#34");
Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X1>()), "#35");
Assert.IsTrue (CanConvert<I7<X2>>(new Y2X1()), "#36");
Assert.IsFalse(CanConvert<I7<X1>>(new Y2<X2>()), "#37");
Assert.IsFalse(CanConvert<I7<X1>>(new Y2X2()), "#38");
Assert.IsTrue (CanConvert<I7<X2>>(new Y2<X2>()), "#39");
Assert.IsTrue (CanConvert<I7<X2>>(new Y2X2()), "#40");
Assert.IsFalse(CanConvert<I1>(new Y3<X1, X1>()), "#41");
Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X1, X1>()), "#42");
Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X1X1()), "#43");
Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X1, X2>()), "#44");
Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X1X2()), "#45");
Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3<X2, X1>()), "#46");
Assert.IsTrue (CanConvert<I8<X1, X1>>(new Y3X2X1()), "#47");
Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3<X2, X2>()), "#48");
Assert.IsFalse(CanConvert<I8<X1, X1>>(new Y3X2X2()), "#49");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X1>()), "#50");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X1()), "#51");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X1, X2>()), "#52");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X1X2()), "#53");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X1>()), "#54");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X1()), "#55");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3<X2, X2>()), "#56");
Assert.IsTrue (CanConvert<I8<X1, X2>>(new Y3X2X2()), "#57");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X1>()), "#58");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X1()), "#59");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X1, X2>()), "#60");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X1X2()), "#61");
Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3<X2, X1>()), "#62");
Assert.IsTrue (CanConvert<I8<X2, X1>>(new Y3X2X1()), "#63");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3<X2, X2>()), "#64");
Assert.IsFalse(CanConvert<I8<X2, X1>>(new Y3X2X2()), "#65");
Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X1>()), "#66");
Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X1()), "#67");
Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3<X1, X2>()), "#68");
Assert.IsFalse(CanConvert<I8<X2, X2>>(new Y3X1X2()), "#69");
Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X1>()), "#70");
Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X1()), "#71");
Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3<X2, X2>()), "#72");
Assert.IsTrue (CanConvert<I8<X2, X2>>(new Y3X2X2()), "#73");
Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X1>()), "#74");
Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X1>()), "#75");
Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X1>()), "#76");
Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X1>()), "#77");
Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<string, X1>()), "#78");
Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X1>()), "#79");
Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X1>()), "#80");
Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<object, X1>()), "#81");
Assert.IsTrue (CanConvert<I9<string, X1>>(new Y4<string, X2>()), "#82");
Assert.IsFalse(CanConvert<I9<object, X1>>(new Y4<string, X2>()), "#83");
Assert.IsFalse(CanConvert<I9<string, X1>>(new Y4<object, X2>()), "#84");
Assert.IsTrue (CanConvert<I9<object, X1>>(new Y4<object, X2>()), "#85");
Assert.IsTrue (CanConvert<I9<string, X2>>(new Y4<string, X2>()), "#86");
Assert.IsFalse(CanConvert<I9<object, X2>>(new Y4<string, X2>()), "#87");
Assert.IsFalse(CanConvert<I9<string, X2>>(new Y4<object, X2>()), "#88");
Assert.IsTrue (CanConvert<I9<object, X2>>(new Y4<object, X2>()), "#89");
Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X1, X1>()), "#90");
Assert.IsTrue (CanConvert<I6<I7<X1>>>(new Y5<X1, X1>()), "#91");
Assert.IsFalse(CanConvert<I6<I6<X2>>>(new Y5<X1, X1>()), "#92");
Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X1, X1>()), "#93");
Assert.IsTrue (CanConvert<I6<I8<X1, X1>>>(new Y5<X1, X1>()), "#94");
Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X1, X1>()), "#95");
Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X1, X1>()), "#96");
Assert.IsFalse(CanConvert<I6<I8<X2, X2>>>(new Y5<X1, X1>()), "#97");
Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X1, X1>()), "#98");
Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X1, X1>()), "#99");
Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X1, X1>()), "#100");
Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X1, X1>()), "#101");
Assert.IsTrue (CanConvert<I6<I6<X1>>>(new Y5<X2, X2>()), "#102");
Assert.IsFalse(CanConvert<I6<I7<X1>>>(new Y5<X2, X2>()), "#103");
Assert.IsTrue (CanConvert<I6<I6<X2>>>(new Y5<X2, X2>()), "#104");
Assert.IsTrue (CanConvert<I6<I7<X2>>>(new Y5<X2, X2>()), "#105");
Assert.IsFalse(CanConvert<I6<I8<X1, X1>>>(new Y5<X2, X2>()), "#106");
Assert.IsTrue (CanConvert<I6<I8<X1, X2>>>(new Y5<X2, X2>()), "#107");
Assert.IsFalse(CanConvert<I6<I8<X2, X1>>>(new Y5<X2, X2>()), "#108");
Assert.IsTrue (CanConvert<I6<I8<X2, X2>>>(new Y5<X2, X2>()), "#109");
Assert.IsFalse(CanConvert<I6<I10<X1, X1>>>(new Y5<X2, X2>()), "#110");
Assert.IsFalse(CanConvert<I6<I10<X1, X2>>>(new Y5<X2, X2>()), "#111");
Assert.IsFalse(CanConvert<I6<I10<X2, X1>>>(new Y5<X2, X2>()), "#112");
Assert.IsFalse(CanConvert<I6<I10<X2, X2>>>(new Y5<X2, X2>()), "#113");
Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X1, X1>()), "#114");
Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X1, X1>()), "#115");
Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X1, X1>()), "#116");
Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X1, X1>()), "#117");
Assert.IsTrue (CanConvert<I7<I8<X1, X1>>>(new Y6<X1, X1>()), "#118");
Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X1, X1>()), "#119");
Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X1, X1>()), "#120");
Assert.IsFalse(CanConvert<I7<I8<X2, X2>>>(new Y6<X1, X1>()), "#121");
Assert.IsTrue (CanConvert<I7<I10<X1, X1>>>(new Y6<X1, X1>()), "#122");
Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X1, X1>()), "#123");
Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X1, X1>()), "#124");
Assert.IsFalse(CanConvert<I7<I10<X2, X2>>>(new Y6<X1, X1>()), "#125");
Assert.IsFalse(CanConvert<I7<I6<X1>>>(new Y6<X2, X2>()), "#126");
Assert.IsFalse(CanConvert<I7<I7<X1>>>(new Y6<X2, X2>()), "#127");
Assert.IsFalse(CanConvert<I7<I6<X2>>>(new Y6<X2, X2>()), "#128");
Assert.IsFalse(CanConvert<I7<I7<X2>>>(new Y6<X2, X2>()), "#129");
Assert.IsFalse(CanConvert<I7<I8<X1, X1>>>(new Y6<X2, X2>()), "#130");
Assert.IsFalse(CanConvert<I7<I8<X1, X2>>>(new Y6<X2, X2>()), "#131");
Assert.IsTrue (CanConvert<I7<I8<X2, X1>>>(new Y6<X2, X2>()), "#132");
Assert.IsTrue (CanConvert<I7<I8<X2, X2>>>(new Y6<X2, X2>()), "#133");
Assert.IsFalse(CanConvert<I7<I10<X1, X1>>>(new Y6<X2, X2>()), "#134");
Assert.IsFalse(CanConvert<I7<I10<X1, X2>>>(new Y6<X2, X2>()), "#135");
Assert.IsTrue (CanConvert<I7<I10<X2, X1>>>(new Y6<X2, X2>()), "#136");
Assert.IsTrue (CanConvert<I7<I10<X2, X2>>>(new Y6<X2, X2>()), "#137");
Assert.IsFalse((object)null is object, "#138");
}
[Test]
public void GetTypeWorksOnObjects() {
Action a = () => {};
Assert.AreEqual(new C1().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C1");
Assert.AreEqual(new C2<int>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[[ss.Int32]]");
Assert.AreEqual(new C2<string>().GetType().FullName, "CoreLib.TestScript.Reflection.TypeSystemLanguageSupportTests$C2$1[[String]]");
Assert.AreEqual((1).GetType().FullName, "Number");
Assert.AreEqual("X".GetType().FullName, "String");
Assert.AreEqual(a.GetType().FullName, "Function");
Assert.AreEqual(new object().GetType().FullName, "Object");
Assert.AreEqual(new[] { 1, 2 }.GetType().FullName, "Array");
}
[Test]
public void GetTypeOnNullInstanceThrowsException() {
Assert.Throws(() => ((object)null).GetType());
}
#pragma warning disable 219
private T Cast<T>(object o) {
return (T)o;
}
[Test]
public void CastOperatorForSerializableTypeWithoutTypeCheckCodeAlwaysSucceedsGeneric() {
object o = new object();
var b = Cast<BS>(o);
Assert.IsTrue(ReferenceEquals(o, b));
}
[Test]
public void CastOperatorsWorkForSerializableTypesWithCustomTypeCheckCodeGeneric() {
object o1 = new { x = 1 };
object o2 = new { x = 1, y = 2 };
Assert.Throws<InvalidCastException>(() => { var x = Cast<DS>(o1); });
var ds = Cast<DS>(o2);
Assert.IsTrue(ReferenceEquals(o2, ds));
}
[Test]
public void CastOperatorsWorkForSerializableTypesWithCustomTypeCheckCode() {
object o1 = new { x = 1 };
object o2 = new { x = 1, y = 2 };
Assert.IsFalse(o1 is DS, "o1 should not be of type");
Assert.IsTrue (o2 is DS, "o2 should be of type");
Assert.AreStrictEqual(o1 as DS, null, "Try cast o1 to type should be null");
Assert.IsTrue((o2 as DS) == o2, "Try cast o2 to type should return o2");
Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw");
Assert.IsTrue((DS)o2 == o2, "Cast o2 to type should return o2");
}
[Test]
public void CastOperatorsWorkForImportedTypesWithCustomTypeCheckCode() {
object o1 = new { x = 1 };
object o2 = new { x = 1, y = 2 };
Assert.IsFalse(o1 is CI, "o1 should not be of type");
Assert.IsTrue (o2 is CI, "o2 should be of type");
Assert.AreStrictEqual(o1 as CI, null, "Try cast o1 to type should be null");
Assert.IsTrue((o2 as CI) == o2, "Try cast o2 to type should return o2");
Assert.Throws(() => { object x = (DS)o1; }, "Cast o1 to type should throw");
Assert.IsTrue((CI)o2 == o2, "Cast o2 to type should return o2");
}
#pragma warning restore 219
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record
{
using System;
using System.Text;
using NPOI.Util;
using NPOI.HSSF.Util;
using NPOI.SS.Util;
/**
* The <c>HyperlinkRecord</c> wraps an HLINK-record
* from the Excel-97 format.
* Supports only external links for now (eg http://)
*
* @author Mark Hissink Muller <a href="mailto:mark@hissinkmuller.nl">mark@hissinkmuller.nl</a>
* @author Yegor Kozlov (yegor at apache dot org)
*/
public class HyperlinkRecord : StandardRecord
{
private static POILogger logger = POILogFactory.GetLogger(typeof(HyperlinkRecord));
/**
* Link flags
*/
public const int HLINK_URL = 0x01; // File link or URL.
public const int HLINK_ABS = 0x02; // Absolute path.
public const int HLINK_LABEL = 0x14; // Has label.
public const int HLINK_PLACE = 0x08; // Place in worksheet.
private const int HLINK_TARGET_FRAME = 0x80; // has 'target frame'
private const int HLINK_UNC_PATH = 0x100; // has UNC path
public static readonly GUID STD_MONIKER = GUID.Parse("79EAC9D0-BAF9-11CE-8C82-00AA004BA90B");
public static readonly GUID URL_MONIKER = GUID.Parse("79EAC9E0-BAF9-11CE-8C82-00AA004BA90B");
public static readonly GUID FILE_MONIKER = GUID.Parse("00000303-0000-0000-C000-000000000046");
/**
* Tail of a URL link
*/
public static readonly byte[] URL_uninterpretedTail = HexRead.ReadFromString("79 58 81 F4 3B 1D 7F 48 AF 2C 82 5D C4 85 27 63 00 00 00 00 A5 AB 00 00");
/**
* Tail of a file link
*/
public static readonly byte[] FILE_uninterpretedTail = HexRead.ReadFromString("FF FF AD DE 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00");
private static readonly int TAIL_SIZE = FILE_uninterpretedTail.Length;
public const short sid = 0x1b8;
/** cell range of this hyperlink */
private CellRangeAddress _range;
/**
* 16-byte GUID
*/
private GUID _guid;
/**
* Some sort of options for file links.
*/
private short _fileOpts;
/**
* Link options. Can include any of HLINK_* flags.
*/
private int _linkOpts;
/**
* Test label
*/
private String _label=string.Empty;
private String _targetFrame=string.Empty;
/**
* Moniker. Makes sense only for URL and file links
*/
private GUID _moniker;
/** in 8:3 DOS format No Unicode string header,
* always 8-bit characters, zero-terminated */
private String _shortFilename=string.Empty;
/** Link */
private String _address=string.Empty;
/**
* Text describing a place in document. In Excel UI, this is appended to the
* address, (after a '#' delimiter).<br/>
* This field is optional. If present, the {@link #HLINK_PLACE} must be set.
*/
private String _textMark=string.Empty;
/**
* Remaining bytes
*/
private byte[] _uninterpretedTail;
/**
* Create a new hyperlink
*/
public HyperlinkRecord()
{
}
/**
* Read hyperlink from input stream
*
* @param in the stream to Read from
*/
public HyperlinkRecord(RecordInputStream in1)
{
_range = new CellRangeAddress(in1);
// 16-byte GUID
_guid = new GUID(in1);
/*
* streamVersion (4 bytes): An unsigned integer that specifies the version number
* of the serialization implementation used to save this structure. This value MUST equal 2.
*/
int streamVersion = in1.ReadInt();
if (streamVersion != 0x00000002)
{
throw new RecordFormatException("Stream Version must be 0x2 but found " + streamVersion);
}
_linkOpts = in1.ReadInt();
if ((_linkOpts & HLINK_LABEL) != 0)
{
int label_len = in1.ReadInt();
_label = in1.ReadUnicodeLEString(label_len);
}
if ((_linkOpts & HLINK_TARGET_FRAME) != 0)
{
int len = in1.ReadInt();
_targetFrame = in1.ReadUnicodeLEString(len);
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) != 0)
{
_moniker = null;
int nChars = in1.ReadInt();
_address = in1.ReadUnicodeLEString(nChars);
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) == 0)
{
_moniker = new GUID(in1);
if (URL_MONIKER.Equals(_moniker))
{
int length = in1.ReadInt();
/*
* The value of <code>length<code> be either the byte size of the url field
* (including the terminating NULL character) or the byte size of the url field plus 24.
* If the value of this field is set to the byte size of the url field,
* then the tail bytes fields are not present.
*/
int remaining = in1.Remaining;
if (length == remaining)
{
int nChars = length / 2;
_address = in1.ReadUnicodeLEString(nChars);
}
else
{
int nChars = (length - TAIL_SIZE) / 2;
_address = in1.ReadUnicodeLEString(nChars);
/*
* TODO: make sense of the remaining bytes
* According to the spec they consist of:
* 1. 16-byte GUID: This field MUST equal
* {0xF4815879, 0x1D3B, 0x487F, 0xAF, 0x2C, 0x82, 0x5D, 0xC4, 0x85, 0x27, 0x63}
* 2. Serial version, this field MUST equal 0 if present.
* 3. URI Flags
*/
_uninterpretedTail = ReadTail(URL_uninterpretedTail, in1);
}
}
else if (FILE_MONIKER.Equals(_moniker))
{
_fileOpts = in1.ReadShort();
int len = in1.ReadInt();
_shortFilename = StringUtil.ReadCompressedUnicode(in1, len);
_uninterpretedTail = ReadTail(FILE_uninterpretedTail, in1);
int size = in1.ReadInt();
if (size > 0)
{
int charDataSize = in1.ReadInt();
//From the spec: An optional unsigned integer that MUST be 3 if present
// but some files has 4
int usKeyValue = in1.ReadUShort();
_address = StringUtil.ReadUnicodeLE(in1, charDataSize / 2);
}
else
{
_address = null;
}
}
else if (STD_MONIKER.Equals(_moniker))
{
_fileOpts = in1.ReadShort();
int len = in1.ReadInt();
byte[] path_bytes = new byte[len];
in1.ReadFully(path_bytes);
_address = Encoding.UTF8.GetString(path_bytes);
}
}
if ((_linkOpts & HLINK_PLACE) != 0)
{
int len = in1.ReadInt();
_textMark = in1.ReadUnicodeLEString(len);
}
if (in1.Remaining > 0)
{
Console.WriteLine(HexDump.ToHex(in1.ReadRemainder()));
}
}
private static byte[] ReadTail(byte[] expectedTail, ILittleEndianInput in1)
{
byte[] result = new byte[TAIL_SIZE];
in1.ReadFully(result);
//if (false)
//{ // Quite a few examples in the unit tests which don't have the exact expected tail
// for (int i = 0; i < expectedTail.Length; i++)
// {
// if (expectedTail[i] != result[i])
// {
// logger.Log( POILogger.ERROR, "Mismatch in tail byte [" + i + "]"
// + "expected " + (expectedTail[i] & 0xFF) + " but got " + (result[i] & 0xFF));
// }
// }
//}
return result;
}
private static void WriteTail(byte[] tail, ILittleEndianOutput out1)
{
out1.Write(tail);
}
/**
* Return the column of the first cell that Contains the hyperlink
*
* @return the 0-based column of the first cell that Contains the hyperlink
*/
public int FirstColumn
{
get{return _range.FirstColumn;}
set{_range.FirstColumn = value;}
}
/**
* Set the column of the last cell that Contains the hyperlink
*
* @return the 0-based column of the last cell that Contains the hyperlink
*/
public int LastColumn
{
get{return _range.LastColumn;}
set{_range.LastColumn= value;}
}
/**
* Return the row of the first cell that Contains the hyperlink
*
* @return the 0-based row of the first cell that Contains the hyperlink
*/
public int FirstRow
{
get{ return _range.FirstRow;}
set{_range.FirstRow = value;}
}
/**
* Return the row of the last cell that Contains the hyperlink
*
* @return the 0-based row of the last cell that Contains the hyperlink
*/
public int LastRow
{
get { return _range.LastRow; }
set { _range.LastRow = value; }
}
/**
* Returns a 16-byte guid identifier. Seems to always equal {@link STD_MONIKER}
*
* @return 16-byte guid identifier
*/
public GUID Guid
{
get
{
return _guid;
}
}
/**
* Returns a 16-byte moniker.
*
* @return 16-byte moniker
*/
public GUID Moniker
{
get
{
return _moniker;
}
}
private static String CleanString(String s)
{
if (s == null)
{
return null;
}
int idx = s.IndexOf('\u0000');
if (idx < 0)
{
return s;
}
return s.Substring(0, idx);
}
private static String AppendNullTerm(String s)
{
if (s == null)
{
return null;
}
return s + '\u0000';
}
/**
* Return text label for this hyperlink
*
* @return text to Display
*/
public String Label
{
get
{
return CleanString(_label);
}
set
{
_label = AppendNullTerm(value);
}
}
/**
* Hypelink Address. Depending on the hyperlink type it can be URL, e-mail, patrh to a file, etc.
*
* @return the Address of this hyperlink
*/
public String Address
{
get
{
if ((_linkOpts & HLINK_URL) != 0 && _moniker!=null && FILE_MONIKER.Equals(_moniker))
return CleanString(_address != null ? _address : _shortFilename);
else if ((_linkOpts & HLINK_PLACE) != 0)
return CleanString(_textMark);
else
return CleanString(_address);
}
set
{
if ((_linkOpts & HLINK_URL) != 0 && _moniker != null && FILE_MONIKER.Equals(_moniker))
_shortFilename = AppendNullTerm(value);
else if ((_linkOpts & HLINK_PLACE) != 0)
_textMark = AppendNullTerm(value);
else
_address = AppendNullTerm(value);
}
}
public String TextMark
{
get
{
return CleanString(_textMark);
}
set
{
_textMark = AppendNullTerm(value);
}
}
/**
* Link options. Must be a combination of HLINK_* constants.
*/
public int LinkOptions
{
get
{
return _linkOpts;
}
}
public String TargetFrame
{
get
{
return CleanString(_targetFrame);
}
}
public String ShortFilename
{
get
{
return CleanString(_shortFilename);
}
set
{
_shortFilename = AppendNullTerm(value);
}
}
/**
* Label options
*/
public int LabelOptions
{
get
{
return 2;
}
}
/**
* Options for a file link
*/
public int FileOptions
{
get
{
return _fileOpts;
}
}
public override short Sid
{
get { return HyperlinkRecord.sid; }
}
public override void Serialize(ILittleEndianOutput out1)
{
_range.Serialize(out1);
_guid.Serialize(out1);
out1.WriteInt(0x00000002); // TODO const
out1.WriteInt(_linkOpts);
if ((_linkOpts & HLINK_LABEL) != 0)
{
out1.WriteInt(_label.Length);
StringUtil.PutUnicodeLE(_label, out1);
}
if ((_linkOpts & HLINK_TARGET_FRAME) != 0)
{
out1.WriteInt(_targetFrame.Length);
StringUtil.PutUnicodeLE(_targetFrame, out1);
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) != 0)
{
out1.WriteInt(_address.Length);
StringUtil.PutUnicodeLE(_address, out1);
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) == 0)
{
_moniker.Serialize(out1);
if (_moniker != null && URL_MONIKER.Equals(_moniker))
{
if (_uninterpretedTail == null)
{
out1.WriteInt(_address.Length * 2);
StringUtil.PutUnicodeLE(_address, out1);
}
else
{
out1.WriteInt(_address.Length * 2 + TAIL_SIZE);
StringUtil.PutUnicodeLE(_address, out1);
WriteTail(_uninterpretedTail, out1);
}
}
else if (_moniker != null && FILE_MONIKER.Equals(_moniker))
{
out1.WriteShort(_fileOpts);
out1.WriteInt(_shortFilename.Length);
StringUtil.PutCompressedUnicode(_shortFilename, out1);
WriteTail(_uninterpretedTail, out1);
if (string.IsNullOrEmpty(_address))
{
out1.WriteInt(0);
}
else
{
int addrLen = _address.Length * 2;
out1.WriteInt(addrLen + 6);
out1.WriteInt(addrLen);
out1.WriteShort(0x0003); // TODO const
StringUtil.PutUnicodeLE(_address, out1);
}
}
}
if ((_linkOpts & HLINK_PLACE) != 0)
{
out1.WriteInt(_textMark.Length);
StringUtil.PutUnicodeLE(_textMark, out1);
}
}
protected override int DataSize
{
get
{
int size = 0;
size += 2 + 2 + 2 + 2; //rwFirst, rwLast, colFirst, colLast
size += GUID.ENCODED_SIZE;
size += 4; //label_opts
size += 4; //_linkOpts
if ((_linkOpts & HLINK_LABEL) != 0)
{
size += 4; //link Length
size += _label.Length * 2;
}
if ((_linkOpts & HLINK_TARGET_FRAME) != 0)
{
size += 4; // int nChars
size += _targetFrame.Length * 2;
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) != 0)
{
size += 4; // int nChars
size += _address.Length * 2;
}
if ((_linkOpts & HLINK_URL) != 0 && (_linkOpts & HLINK_UNC_PATH) == 0)
{
size += GUID.ENCODED_SIZE; //moniker Length
if (_moniker!=null&&URL_MONIKER.Equals(_moniker))
{
size += 4; //Address Length
size += _address.Length * 2;
if (_uninterpretedTail != null)
{
size += TAIL_SIZE;
}
}
else if (_moniker != null && FILE_MONIKER.Equals(_moniker))
{
size += 2; //_fileOpts
size += 4; //Address Length
size += _shortFilename == null ? 0 : _shortFilename.Length;
size += TAIL_SIZE;
size += 4;
if (!string.IsNullOrEmpty(_address))
{
size += 6;
size += _address.Length * 2;
}
}
}
if ((_linkOpts & HLINK_PLACE) != 0)
{
size += 4; //Address Length
size += _textMark.Length * 2;
}
return size;
}
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder();
buffer.Append("[HYPERLINK RECORD]\n");
buffer.Append(" .range = ").Append(_range.FormatAsString()).Append("\n");
buffer.Append(" .guid = ").Append(_guid.FormatAsString()).Append("\n");
buffer.Append(" .linkOpts = ").Append(HexDump.IntToHex(this._linkOpts)).Append("\n");
buffer.Append(" .label = ").Append(Label).Append("\n");
if ((_linkOpts & HLINK_TARGET_FRAME) != 0)
{
buffer.Append(" .targetFrame= ").Append(TargetFrame).Append("\n");
}
if((_linkOpts & HLINK_URL) != 0 && _moniker != null)
{
buffer.Append(" .moniker = ").Append(_moniker.FormatAsString()).Append("\n");
}
if ((_linkOpts & HLINK_PLACE) != 0)
{
buffer.Append(" .targetFrame= ").Append(TextMark).Append("\n");
}
buffer.Append(" .address = ").Append(Address).Append("\n");
buffer.Append("[/HYPERLINK RECORD]\n");
return buffer.ToString();
}
/// <summary>
/// Initialize a new url link
/// </summary>
public void CreateUrlLink()
{
_range = new CellRangeAddress(0, 0, 0, 0);
_guid = STD_MONIKER;
_linkOpts = HLINK_URL | HLINK_ABS | HLINK_LABEL;
Label = "";
_moniker = URL_MONIKER;
Address = "";
_uninterpretedTail = URL_uninterpretedTail;
}
/// <summary>
/// Initialize a new file link
/// </summary>
public void CreateFileLink()
{
_range = new CellRangeAddress(0, 0, 0, 0);
_guid = STD_MONIKER;
_linkOpts = HLINK_URL | HLINK_LABEL;
_fileOpts = 0;
Label = "";
_moniker = FILE_MONIKER;
Address= null;
ShortFilename = "";
_uninterpretedTail = FILE_uninterpretedTail;
}
/// <summary>
/// Initialize a new document link
/// </summary>
public void CreateDocumentLink()
{
_range = new CellRangeAddress(0, 0, 0, 0);
_guid = STD_MONIKER;
_linkOpts = HLINK_LABEL | HLINK_PLACE;
Label = "";
_moniker = FILE_MONIKER;
Address = "";
TextMark = "";
}
public override Object Clone()
{
HyperlinkRecord rec = new HyperlinkRecord();
rec._range = _range.Copy();
rec._guid = _guid;
rec._linkOpts = _linkOpts;
rec._fileOpts = _fileOpts;
rec._label = _label;
rec._address = _address;
rec._moniker = _moniker;
rec._shortFilename = _shortFilename;
rec._targetFrame = _targetFrame;
rec._textMark = _textMark;
rec._uninterpretedTail = _uninterpretedTail;
return rec;
}
}
}
| |
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob.Protocol;
using Microsoft.WindowsAzure.Storage.Core;
using Microsoft.WindowsAzure.Storage.Core.Auth;
using Microsoft.WindowsAzure.Storage.Core.Executor;
using Microsoft.WindowsAzure.Storage.Core.Util;
using Microsoft.WindowsAzure.Storage.Shared.Protocol;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.WindowsAzure.Storage.Blob
{
public class CloudBlobContainer
{
public CloudBlobClient ServiceClient
{
get; private set;
}
public Uri Uri
{
get
{
throw new System.NotImplementedException();
}
}
public StorageUri StorageUri
{
get; private set;
}
public string Name
{
get; private set;
}
public IDictionary<string, string> Metadata
{
get; private set;
}
public BlobContainerProperties Properties
{
get; private set;
}
public CloudBlobContainer(Uri containerAddress)
: this(containerAddress, (StorageCredentials) null)
{
throw new System.NotImplementedException();
}
public CloudBlobContainer(Uri containerAddress, StorageCredentials credentials)
: this(new StorageUri(containerAddress), credentials)
{
throw new System.NotImplementedException();
}
public CloudBlobContainer(StorageUri containerAddress, StorageCredentials credentials)
{
throw new System.NotImplementedException();
}
internal CloudBlobContainer(string containerName, CloudBlobClient serviceClient)
: this(new BlobContainerProperties(), (IDictionary<string, string>) new Dictionary<string, string>(), containerName, serviceClient)
{
throw new System.NotImplementedException();
}
internal CloudBlobContainer(BlobContainerProperties properties, IDictionary<string, string> metadata, string containerName, CloudBlobClient serviceClient)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task CreateAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> CreateIfNotExistsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> CreateIfNotExistsAsync(BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> CreateIfNotExistsAsync(BlobContainerPublicAccessType accessType, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task DeleteAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> DeleteIfExistsAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(string blobName)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(string blobName, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<ICloudBlob> GetBlobReferenceFromServerAsync(string blobName, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(BlobContinuationToken currentToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, BlobContinuationToken currentToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobResultSegment> ListBlobsSegmentedAsync(string prefix, bool useFlatBlobListing, BlobListingDetails blobListingDetails, int? maxResults, BlobContinuationToken currentToken, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPermissionsAsync(BlobContainerPermissions permissions)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPermissionsAsync(BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetPermissionsAsync(BlobContainerPermissions permissions, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobContainerPermissions> GetPermissionsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobContainerPermissions> GetPermissionsAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<BlobContainerPermissions> GetPermissionsAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> ExistsAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<bool> ExistsAsync(BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
public virtual Task<bool> ExistsAsync(BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
public virtual Task FetchAttributesAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task FetchAttributesAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task FetchAttributesAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync()
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task SetMetadataAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> AcquireLeaseAsync(TimeSpan? leaseTime, string proposedLeaseId = null)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> AcquireLeaseAsync(TimeSpan? leaseTime, string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> AcquireLeaseAsync(TimeSpan? leaseTime, string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task RenewLeaseAsync(AccessCondition accessCondition)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task RenewLeaseAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task RenewLeaseAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> ChangeLeaseAsync(string proposedLeaseId, AccessCondition accessCondition)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> ChangeLeaseAsync(string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<string> ChangeLeaseAsync(string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ReleaseLeaseAsync(AccessCondition accessCondition)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ReleaseLeaseAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task ReleaseLeaseAsync(AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<TimeSpan> BreakLeaseAsync(TimeSpan? breakPeriod)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<TimeSpan> BreakLeaseAsync(TimeSpan? breakPeriod, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
{
throw new System.NotImplementedException();
}
[DoesServiceRequest]
public virtual Task<TimeSpan> BreakLeaseAsync(TimeSpan? breakPeriod, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken)
{
throw new System.NotImplementedException();
}
internal RESTCommand<string> AcquireLeaseImpl(TimeSpan? leaseTime, string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
internal RESTCommand<NullType> RenewLeaseImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
internal RESTCommand<string> ChangeLeaseImpl(string proposedLeaseId, AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
internal RESTCommand<NullType> ReleaseLeaseImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
internal RESTCommand<TimeSpan> BreakLeaseImpl(TimeSpan? breakPeriod, AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> CreateContainerImpl(BlobRequestOptions options, BlobContainerPublicAccessType accessType)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> DeleteContainerImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> FetchAttributesImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<bool> ExistsImpl(BlobRequestOptions options, bool primaryOnly)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> SetMetadataImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<NullType> SetPermissionsImpl(BlobContainerPermissions acl, AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private RESTCommand<BlobContainerPermissions> GetPermissionsImpl(AccessCondition accessCondition, BlobRequestOptions options)
{
throw new System.NotImplementedException();
}
private IListBlobItem SelectListBlobItem(IListBlobEntry protocolItem)
{
throw new System.NotImplementedException();
}
private RESTCommand<ResultSegment<IListBlobItem>> ListBlobsImpl(string prefix, int? maxResults, bool useFlatBlobListing, BlobListingDetails blobListingDetails, BlobRequestOptions options, BlobContinuationToken currentToken)
{
throw new System.NotImplementedException();
}
private void ParseQueryAndVerify(StorageUri address, StorageCredentials credentials)
{
throw new System.NotImplementedException();
}
private string GetSharedAccessCanonicalName()
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessBlobPolicy policy)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, string groupPolicyIdentifier)
{
throw new System.NotImplementedException();
}
public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, string groupPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange)
{
throw new System.NotImplementedException();
}
public virtual CloudPageBlob GetPageBlobReference(string blobName)
{
throw new System.NotImplementedException();
}
public virtual CloudPageBlob GetPageBlobReference(string blobName, DateTimeOffset? snapshotTime)
{
throw new System.NotImplementedException();
}
public virtual CloudBlockBlob GetBlockBlobReference(string blobName)
{
throw new System.NotImplementedException();
}
public virtual CloudBlockBlob GetBlockBlobReference(string blobName, DateTimeOffset? snapshotTime)
{
throw new System.NotImplementedException();
}
public virtual CloudAppendBlob GetAppendBlobReference(string blobName)
{
throw new System.NotImplementedException();
}
public virtual CloudAppendBlob GetAppendBlobReference(string blobName, DateTimeOffset? snapshotTime)
{
throw new System.NotImplementedException();
}
public virtual CloudBlob GetBlobReference(string blobName)
{
throw new System.NotImplementedException();
}
public virtual CloudBlob GetBlobReference(string blobName, DateTimeOffset? snapshotTime)
{
throw new System.NotImplementedException();
}
public virtual CloudBlobDirectory GetDirectoryReference(string relativeAddress)
{
throw new System.NotImplementedException();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using log4net;
using log4net.Appender;
using log4net.Core;
using log4net.Repository;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using Timer=System.Timers.Timer;
using Nini.Config;
namespace OpenSim.Framework.Servers
{
/// <summary>
/// Common base for the main OpenSimServers (user, grid, inventory, region, etc)
/// </summary>
public abstract class BaseOpenSimServer : ServerBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Used by tests to suppress Environment.Exit(0) so that post-run operations are possible.
/// </summary>
public bool SuppressExit { get; set; }
/// <summary>
/// This will control a periodic log printout of the current 'show stats' (if they are active) for this
/// server.
/// </summary>
private int m_periodDiagnosticTimerMS = 60 * 60 * 1000;
private Timer m_periodicDiagnosticsTimer = new Timer(60 * 60 * 1000);
/// <summary>
/// Random uuid for private data
/// </summary>
protected string m_osSecret = String.Empty;
protected BaseHttpServer m_httpServer;
public BaseHttpServer HttpServer
{
get { return m_httpServer; }
}
public BaseOpenSimServer() : base()
{
// Random uuid for private data
m_osSecret = UUID.Random().ToString();
}
/// <summary>
/// Must be overriden by child classes for their own server specific startup behaviour.
/// </summary>
protected virtual void StartupSpecific()
{
StatsManager.SimExtraStats = new SimExtraStatsCollector();
RegisterCommonCommands();
RegisterCommonComponents(Config);
IConfig startupConfig = Config.Configs["Startup"];
int logShowStatsSeconds = startupConfig.GetInt("LogShowStatsSeconds", m_periodDiagnosticTimerMS / 1000);
m_periodDiagnosticTimerMS = logShowStatsSeconds * 1000;
m_periodicDiagnosticsTimer.Elapsed += new ElapsedEventHandler(LogDiagnostics);
if (m_periodDiagnosticTimerMS != 0)
{
m_periodicDiagnosticsTimer.Interval = m_periodDiagnosticTimerMS;
m_periodicDiagnosticsTimer.Enabled = true;
}
}
protected override void ShutdownSpecific()
{
Watchdog.Enabled = false;
base.ShutdownSpecific();
MainServer.Stop();
Thread.Sleep(5000);
Util.StopThreadPool();
WorkManager.Stop();
Thread.Sleep(1000);
RemovePIDFile();
m_log.Info("[SHUTDOWN]: Shutdown processing on main thread complete. Exiting...");
if (!SuppressExit)
Environment.Exit(0);
}
/// <summary>
/// Provides a list of help topics that are available. Overriding classes should append their topics to the
/// information returned when the base method is called.
/// </summary>
///
/// <returns>
/// A list of strings that represent different help topics on which more information is available
/// </returns>
protected virtual List<string> GetHelpTopics() { return new List<string>(); }
/// <summary>
/// Print statistics to the logfile, if they are active
/// </summary>
protected void LogDiagnostics(object source, ElapsedEventArgs e)
{
StringBuilder sb = new StringBuilder("DIAGNOSTICS\n\n");
sb.Append(GetUptimeReport());
sb.Append(StatsManager.SimExtraStats.Report());
sb.Append(Environment.NewLine);
sb.Append(GetThreadsReport());
m_log.Debug(sb);
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public virtual void Startup()
{
m_log.Info("[STARTUP]: Beginning startup processing");
m_log.Info("[STARTUP]: version: " + m_version + Environment.NewLine);
// clr version potentially is more confusing than helpful, since it doesn't tell us if we're running under Mono/MS .NET and
// the clr version number doesn't match the project version number under Mono.
//m_log.Info("[STARTUP]: Virtual machine runtime version: " + Environment.Version + Environment.NewLine);
m_log.InfoFormat(
"[STARTUP]: Operating system version: {0}, .NET platform {1}, {2}-bit\n",
Environment.OSVersion, Environment.OSVersion.Platform, Util.Is64BitProcess() ? "64" : "32");
try
{
StartupSpecific();
}
catch(Exception e)
{
m_log.Fatal("Fatal error: " + e.ToString());
Environment.Exit(1);
}
TimeSpan timeTaken = DateTime.Now - m_startuptime;
// MainConsole.Instance.OutputFormat(
// "PLEASE WAIT FOR LOGINS TO BE ENABLED ON REGIONS ONCE SCRIPTS HAVE STARTED. Non-script portion of startup took {0}m {1}s.",
// timeTaken.Minutes, timeTaken.Seconds);
}
public string osSecret
{
// Secret uuid for the simulator
get { return m_osSecret; }
}
public string StatReport(IOSHttpRequest httpRequest)
{
// If we catch a request for "callback", wrap the response in the value for jsonp
if (httpRequest.Query.ContainsKey("callback"))
{
return httpRequest.Query["callback"].ToString() + "(" + StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version) + ");";
}
else
{
return StatsManager.SimExtraStats.XReport((DateTime.Now - m_startuptime).ToString() , m_version);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERLevel;
namespace ParentLoad.Business.ERLevel
{
/// <summary>
/// A07_RegionColl (editable child list).<br/>
/// This is a generated base class of <see cref="A07_RegionColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="A06_Country"/> editable child object.<br/>
/// The items of the collection are <see cref="A08_Region"/> objects.
/// </remarks>
[Serializable]
public partial class A07_RegionColl : BusinessListBase<A07_RegionColl, A08_Region>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="A08_Region"/> item from the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to be removed.</param>
public void Remove(int region_ID)
{
foreach (var a08_Region in this)
{
if (a08_Region.Region_ID == region_ID)
{
Remove(a08_Region);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="A08_Region"/> item is in the collection.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the A08_Region is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int region_ID)
{
foreach (var a08_Region in this)
{
if (a08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="A08_Region"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="region_ID">The Region_ID of the item to search for.</param>
/// <returns><c>true</c> if the A08_Region is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int region_ID)
{
foreach (var a08_Region in DeletedList)
{
if (a08_Region.Region_ID == region_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="A08_Region"/> item of the <see cref="A07_RegionColl"/> collection, based on item key properties.
/// </summary>
/// <param name="region_ID">The Region_ID.</param>
/// <returns>A <see cref="A08_Region"/> object.</returns>
public A08_Region FindA08_RegionByParentProperties(int region_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].Region_ID.Equals(region_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="A07_RegionColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="A07_RegionColl"/> collection.</returns>
internal static A07_RegionColl NewA07_RegionColl()
{
return DataPortal.CreateChild<A07_RegionColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="A07_RegionColl"/> object from the given list of A08_RegionDto.
/// </summary>
/// <param name="data">The list of <see cref="A08_RegionDto"/>.</param>
/// <returns>A reference to the fetched <see cref="A07_RegionColl"/> object.</returns>
internal static A07_RegionColl GetA07_RegionColl(List<A08_RegionDto> data)
{
A07_RegionColl obj = new A07_RegionColl();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="A07_RegionColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public A07_RegionColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads all <see cref="A07_RegionColl"/> collection items from the given list of A08_RegionDto.
/// </summary>
/// <param name="data">The list of <see cref="A08_RegionDto"/>.</param>
private void Fetch(List<A08_RegionDto> data)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
var args = new DataPortalHookArgs(data);
OnFetchPre(args);
foreach (var dto in data)
{
Add(A08_Region.GetA08_Region(dto));
}
OnFetchPost(args);
RaiseListChangedEvents = rlce;
}
/// <summary>
/// Loads <see cref="A08_Region"/> items on the A07_RegionObjects collection.
/// </summary>
/// <param name="collection">The grand parent <see cref="A05_CountryColl"/> collection.</param>
internal void LoadItems(A05_CountryColl collection)
{
foreach (var item in this)
{
var obj = collection.FindA06_CountryByParentProperties(item.parent_Country_ID);
var rlce = obj.A07_RegionObjects.RaiseListChangedEvents;
obj.A07_RegionObjects.RaiseListChangedEvents = false;
obj.A07_RegionObjects.Add(item);
obj.A07_RegionObjects.RaiseListChangedEvents = rlce;
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Cytoid.Storyboard.Controllers;
using Cytoid.Storyboard.Sprites;
using Cytoid.Storyboard.Texts;
using Cytoid.Storyboard.Videos;
using Cysharp.Threading.Tasks;
using Newtonsoft.Json;
using UnityEngine;
using LineRenderer = Cytoid.Storyboard.Sprites.LineRenderer;
using SpriteRenderer = Cytoid.Storyboard.Sprites.SpriteRenderer;
namespace Cytoid.Storyboard
{
public class StoryboardRenderer
{
public const int ReferenceWidth = 800;
public const int ReferenceHeight = 600;
public Storyboard Storyboard { get; }
public Game Game => Storyboard.Game;
public Camera Camera { get; private set; }
public float Time => Game.Time;
public StoryboardRendererProvider Provider => StoryboardRendererProvider.Instance;
public readonly Dictionary<string, StoryboardComponentRenderer> ComponentRenderers =
new Dictionary<string, StoryboardComponentRenderer>(); // Object ID to renderer instance
public readonly Dictionary<Type, List<StoryboardComponentRenderer>> TypedComponentRenderers =
new Dictionary<Type, List<StoryboardComponentRenderer>>();
public readonly Dictionary<string, int> SpritePathRefCount = new Dictionary<string, int>();
public StoryboardConstants Constants { get; } = new StoryboardConstants();
public class StoryboardConstants
{
public float CanvasToWorldXMultiplier;
public float CanvasToWorldYMultiplier;
public float WorldToCanvasXMultiplier;
public float WorldToCanvasYMultiplier;
}
public StoryboardRenderer(Storyboard storyboard)
{
Storyboard = storyboard;
}
public void Clear()
{
ComponentRenderers.Values.ForEach(it => it.Clear());
ResetCamera();
ResetCameraFilters();
var canvas = Provider.CanvasRect;
Constants.CanvasToWorldXMultiplier = 1.0f / canvas.width * Camera.pixelWidth;
Constants.CanvasToWorldYMultiplier = 1.0f / canvas.height * Camera.pixelHeight;
Constants.WorldToCanvasXMultiplier = 1.0f / Camera.pixelWidth * canvas.width;
Constants.WorldToCanvasYMultiplier = 1.0f / Camera.pixelHeight * canvas.height;
}
private void ResetCamera()
{
Camera = Provider.Camera;
var cameraTransform = Camera.transform;
cameraTransform.position = new Vector3(0, 0, -10);
cameraTransform.eulerAngles = Vector3.zero;
Camera.orthographic = true;
Camera.fieldOfView = 53.2f;
}
private void ResetCameraFilters()
{
Provider.RadialBlur.Apply(it =>
{
it.enabled = false;
it.Intensity = 0.025f;
});
Provider.ColorAdjustment.Apply(it =>
{
it.enabled = false;
it.Brightness = 1;
it.Saturation = 1;
it.Contrast = 1;
});
Provider.GrayScale.Apply(it =>
{
it.enabled = false;
it._Fade = 1;
});
Provider.Noise.Apply(it =>
{
it.enabled = false;
it.Noise = 0.2f;
});
Provider.ColorFilter.Apply(it =>
{
it.enabled = false;
it.ColorRGB = UnityEngine.Color.white;
});
Provider.Sepia.Apply(it =>
{
it.enabled = false;
it._Fade = 1;
});
Provider.Dream.Apply(it =>
{
it.enabled = false;
it.Distortion = 1;
});
Provider.Fisheye.Apply(it =>
{
it.enabled = false;
it.Distortion = 0.5f;
});
Provider.Shockwave.Apply(it =>
{
it.enabled = false;
it.TimeX = 1.0f;
it.Speed = 1;
});
Provider.Focus.Apply(it =>
{
it.enabled = false;
it.Size = 1;
it.Color = UnityEngine.Color.white;
it.Speed = 5;
it.Intensity = 0.25f;
});
Provider.Glitch.Apply(it =>
{
it.enabled = false;
it.Glitch = 1f;
});
Provider.Artifact.Apply(it =>
{
it.enabled = false;
it.Fade = 1;
it.Colorisation = 1;
it.Parasite = 1;
it.Noise = 1;
});
Provider.Arcade.Apply(it =>
{
it.enabled = false;
it.Interferance_Size = 1;
it.Interferance_Speed = 0.5f;
it.Contrast = 1;
it.Fade = 1;
});
Provider.Chromatical.Apply(it =>
{
it.enabled = false;
it.Fade = 1;
it.Intensity = 1;
it.Speed = 1;
});
Provider.Tape.Apply(it =>
{
it.enabled = false;
});
Provider.SleekRender.Apply(it =>
{
it.enabled = false;
it.settings.bloomEnabled = false;
it.settings.bloomIntensity = 0;
});
}
public void Dispose()
{
ComponentRenderers.Values.ForEach(it => it.Dispose());
ComponentRenderers.Clear();
TypedComponentRenderers.Clear();
SpritePathRefCount.Clear();
Context.AssetMemory.DisposeTaggedCacheAssets(AssetTag.Storyboard);
Clear();
}
public async UniTask Initialize()
{
// Clear
Clear();
foreach (var type in new[]
{typeof(Text), typeof(Sprite), typeof(Line), typeof(Video), typeof(Controller), typeof(NoteController)})
{
TypedComponentRenderers[type] = new List<StoryboardComponentRenderer>();
}
var timer = new BenchmarkTimer("StoryboardRenderer initialization");
bool Predicate<TO>(TO obj) where TO : Object => !obj.IsManuallySpawned(); await SpawnObjects<NoteController, NoteControllerState, NoteControllerRenderer>(Storyboard.NoteControllers.Values.ToList(), noteController => new NoteControllerRenderer(this, noteController), Predicate);
timer.Time("NoteController"); // Spawn note placeholder transforms
await SpawnObjects<Text, TextState, TextRenderer>(Storyboard.Texts.Values.ToList(), text => new TextRenderer(this, text), Predicate);
timer.Time("Text");
await SpawnObjects<Sprite, SpriteState, SpriteRenderer>(Storyboard.Sprites.Values.ToList(), sprite => new SpriteRenderer(this, sprite), Predicate);
timer.Time("Sprite");
await SpawnObjects<Line, LineState, LineRenderer>(Storyboard.Lines.Values.ToList(), line => new LineRenderer(this, line), Predicate);
timer.Time("Line");
await SpawnObjects<Video, VideoState, VideoRenderer>(Storyboard.Videos.Values.ToList(), line => new VideoRenderer(this, line), Predicate);
timer.Time("Video");
await SpawnObjects<Controller, ControllerState, ControllerRenderer>(Storyboard.Controllers.Values.ToList(), controller => new ControllerRenderer(this, controller), Predicate);
timer.Time("Controller");
timer.Time();
// Clear on abort/retry/complete
Game.onGameDisposed.AddListener(_ =>
{
Dispose();
});
Game.onGamePaused.AddListener(_ =>
{
// TODO: Pause SB
});
Game.onGameWillUnpause.AddListener(_ =>
{
// TODO: Unpause SB
});
}
private async UniTask<List<TR>> SpawnObjects<TO, TS, TR>(List<TO> objects, Func<TO, TR> rendererCreator, Predicate<TO> predicate = default, Func<TO, TO> transformer = default)
where TS : ObjectState
where TO : Object<TS>
where TR : StoryboardComponentRenderer<TO, TS>
{
if (predicate == default) predicate = _ => true;
if (transformer == default) transformer = _ => _;
var renderers = new List<TR>();
var tasks = new List<UniTask>();
foreach (var obj in objects)
{
if (!predicate(obj)) continue;
var transformedObj = transformer(obj);
var renderer = rendererCreator(transformedObj);
if (ComponentRenderers.ContainsKey(transformedObj.Id))
{
Debug.LogWarning($"Storyboard: Object {transformedObj.Id} is already spawned");
continue;
}
ComponentRenderers[transformedObj.Id] = renderer;
TypedComponentRenderers[typeof(TO)].Add(renderer);
// Debug.Log($"StoryboardRenderer: Spawned {typeof(TO).Name} with ID {obj.Id}");
// Resolve parent
StoryboardComponentRenderer parent = null;
if (transformedObj.ParentId != null)
{
if (!ComponentRenderers.ContainsKey(transformedObj.ParentId))
{
throw new InvalidOperationException($"Storyboard: parent_id \"{transformedObj.ParentId}\" does not exist");
}
parent = ComponentRenderers[transformedObj.ParentId];
}
else if (transformedObj.TargetId != null)
{
if (!ComponentRenderers.ContainsKey(transformedObj.TargetId))
{
throw new InvalidOperationException($"Storyboard: target_id \"{transformedObj.TargetId}\" does not exist");
}
parent = ComponentRenderers[transformedObj.TargetId] as TR ?? throw new InvalidOperationException($"Storyboard: target_id \"{transformedObj.TargetId} does not have type {typeof(TR).Name}");
}
if (parent != null)
{
parent.Children.Add(renderer);
renderer.Parent = parent;
}
tasks.Add(renderer.Initialize());
}
await UniTask.WhenAll(tasks);
return renderers;
}
public void OnGameUpdate(Game _)
{
var time = Time;
if (time < 0 || Game.State.IsReadyToExit) return;
var updateOrder = new[]
{typeof(NoteController), typeof(Text), typeof(Sprite), typeof(Line), typeof(Video), typeof(Controller)};
var renderersToDestroy = new Dictionary<string, Type>();
foreach (var type in updateOrder)
{
var renderers = TypedComponentRenderers[type];
foreach (var renderer in renderers)
{
renderer.Component.FindStates(time, out var fromState, out var toState);
if (fromState == null) continue;
// Destroy?
if (fromState.Destroy != null && fromState.Destroy.Value)
{
// Destroy the target as well
if (renderer.Parent != null && renderer.Component.TargetId != null)
{
renderersToDestroy[renderer.Parent.Component.Id] = type;
this.ListOf(renderer.Parent).Flatten(it => it.Children).ForEach(it =>
{
renderersToDestroy[it.Component.Id] = type;
});
}
else
{
renderer.Parent?.Children.Remove(renderer);
this.ListOf(renderer).Flatten(it => it.Children).ForEach(it =>
{
renderersToDestroy[it.Component.Id] = type;
});
}
continue;
}
renderer.Update(fromState, toState);
}
}
renderersToDestroy.ForEach(it =>
{
var id = it.Key;
var type = it.Value;
var renderer = ComponentRenderers[id];
if (Game is PlayerGame)
{
renderer.Clear();
}
else
{
renderer.Dispose();
}
ComponentRenderers.Remove(id);
TypedComponentRenderers[type].Remove(renderer);
});
}
public void OnTrigger(Trigger trigger)
{
// Spawn objects
if (trigger.Spawn != null)
{
foreach (var id in trigger.Spawn)
{
SpawnObjectById(id);
}
}
// Destroy objects
if (trigger.Destroy != null)
{
foreach (var id in trigger.Destroy)
{
DestroyObjectsById(id);
}
}
}
public async void SpawnObjectById(string id)
{
bool Predicate<TO>(TO obj) where TO : Object => obj.Id == id;
TO Transformer<TO, TS>(TO obj) where TO : Object<TS> where TS : ObjectState
{
var res = obj.JsonDeepCopy();
RecalculateTime<TO, TS>(res);
return res;
}
if (Storyboard.Texts.ContainsKey(id)) await SpawnObjects<Text, TextState, TextRenderer>(new List<Text> {Storyboard.Texts[id]}, text => new TextRenderer(this, text), Predicate, Transformer<Text, TextState>);
if (Storyboard.Sprites.ContainsKey(id)) await SpawnObjects<Sprite, SpriteState, SpriteRenderer>(new List<Sprite> {Storyboard.Sprites[id]}, sprite => new SpriteRenderer(this, sprite), Predicate, Transformer<Sprite, SpriteState>);
if (Storyboard.Lines.ContainsKey(id)) await SpawnObjects<Line, LineState, LineRenderer>(new List<Line> {Storyboard.Lines[id]}, line => new LineRenderer(this, line), Predicate, Transformer<Line, LineState>);
if (Storyboard.Videos.ContainsKey(id)) await SpawnObjects<Video, VideoState, VideoRenderer>(new List<Video> {Storyboard.Videos[id]}, line => new VideoRenderer(this, line), Predicate, Transformer<Video, VideoState>);
if (Storyboard.Controllers.ContainsKey(id)) await SpawnObjects<Controller, ControllerState, ControllerRenderer>(new List<Controller> {Storyboard.Controllers[id]}, controller => new ControllerRenderer(this, controller), Predicate, Transformer<Controller, ControllerState>);
if (Storyboard.NoteControllers.ContainsKey(id)) await SpawnObjects<NoteController, NoteControllerState, NoteControllerRenderer>(new List<NoteController> {Storyboard.NoteControllers[id]}, noteController => new NoteControllerRenderer(this, noteController), Predicate, Transformer<NoteController, NoteControllerState>);
}
public void DestroyObjectsById(string id)
{
if (!ComponentRenderers.ContainsKey(id)) return;
ComponentRenderers[id].Let(it =>
{
if (Game is PlayerGame) it.Clear();
else it.Dispose();
TypedComponentRenderers[it.GetType()].Remove(it);
});
ComponentRenderers.Remove(id);
}
public void RecalculateTime<TO, TS>(TO obj) where TO : Object<TS> where TS : ObjectState
{
var baseTime = Time;
var states = obj.States;
if (obj.IsManuallySpawned())
{
states[0].Time = baseTime;
}
else
{
baseTime = states[0].Time;
}
var lastTime = baseTime;
foreach (var state in states)
{
if (state.RelativeTime != null)
{
state.Time = baseTime + state.RelativeTime.Value;
}
if (state.AddTime != null)
{
state.Time = lastTime + state.AddTime.Value;
}
lastTime = state.Time;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="DrawListViewColumnHeaderEventArgs.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms
{
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms.Internal;
using Microsoft.Win32;
using System.Windows.Forms.VisualStyles;
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs"]/*' />
/// <devdoc>
/// This class contains the information a user needs to paint ListView column header (Details view only).
/// </devdoc>
public class DrawListViewColumnHeaderEventArgs : EventArgs
{
private readonly Graphics graphics;
private readonly Rectangle bounds;
private readonly int columnIndex;
private readonly ColumnHeader header;
private readonly ListViewItemStates state;
private readonly Color foreColor;
private readonly Color backColor;
private readonly Font font;
private bool drawDefault;
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.DrawListViewColumnHeaderEventArgs"]/*' />
/// <devdoc>
/// Creates a new DrawListViewColumnHeaderEventArgs with the given parameters.
/// </devdoc>
public DrawListViewColumnHeaderEventArgs(Graphics graphics, Rectangle bounds, int columnIndex,
ColumnHeader header, ListViewItemStates state,
Color foreColor, Color backColor, Font font) {
this.graphics = graphics;
this.bounds = bounds;
this.columnIndex = columnIndex;
this.header = header;
this.state = state;
this.foreColor = foreColor;
this.backColor = backColor;
this.font = font;
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.DrawDefault"]/*' />
/// <devdoc>
/// Causes the item do be drawn by the system instead of owner drawn.
/// </devdoc>
public bool DrawDefault {
get {
return drawDefault;
}
set {
drawDefault = value;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.Graphics"]/*' />
/// <devdoc>
/// Graphics object with which painting should be done.
/// </devdoc>
public Graphics Graphics {
get {
return graphics;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.Bounds"]/*' />
/// <devdoc>
/// The rectangle outlining the area in which the painting should be done.
/// </devdoc>
public Rectangle Bounds {
get {
return bounds;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.ColumnIndex"]/*' />
/// <devdoc>
/// The index of this column.
/// </devdoc>
public int ColumnIndex {
get {
return columnIndex;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.Header"]/*' />
/// <devdoc>
/// The header object.
/// </devdoc>
public ColumnHeader Header {
get {
return header;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.State"]/*' />
/// <devdoc>
/// State information pertaining to the header.
/// </devdoc>
public ListViewItemStates State {
get {
return state;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.ForeColor"]/*' />
/// <devdoc>
/// Color used to draw the header's text.
/// </devdoc>
public Color ForeColor {
get {
return foreColor;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.BackColor"]/*' />
/// <devdoc>
/// Color used to draw the header's background.
/// </devdoc>
public Color BackColor {
get {
return backColor;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.Font"]/*' />
/// <devdoc>
/// Font used to render the header's text.
/// </devdoc>
public Font Font {
get {
return font;
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.DrawBackground"]/*' />
/// <devdoc>
/// Draws the header's background.
/// </devdoc>
public void DrawBackground() {
if (Application.RenderWithVisualStyles) {
VisualStyleRenderer vsr = new VisualStyleRenderer(VisualStyleElement.Header.Item.Normal);
vsr.DrawBackground(graphics, bounds);
}
else {
using (Brush backBrush = new SolidBrush(backColor)) {
graphics.FillRectangle(backBrush, bounds);
}
// draw the 3d header
//
Rectangle r = this.bounds;
r.Width -= 1;
r.Height -= 1;
// draw the dark border around the whole thing
//
graphics.DrawRectangle(SystemPens.ControlDarkDark, r);
r.Width -= 1;
r.Height -= 1;
// draw the light 3D border
//
graphics.DrawLine(SystemPens.ControlLightLight, r.X, r.Y, r.Right, r.Y);
graphics.DrawLine(SystemPens.ControlLightLight, r.X, r.Y, r.X, r.Bottom);
// draw the dark 3D Border
//
graphics.DrawLine(SystemPens.ControlDark, r.X + 1, r.Bottom, r.Right, r.Bottom);
graphics.DrawLine(SystemPens.ControlDark, r.Right, r.Y + 1, r.Right, r.Bottom);
}
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.DrawText"]/*' />
/// <devdoc>
/// Draws the header's text (overloaded)
/// </devdoc>
public void DrawText() {
HorizontalAlignment hAlign = header.TextAlign;
TextFormatFlags flags = (hAlign == HorizontalAlignment.Left) ? TextFormatFlags.Left :
((hAlign == HorizontalAlignment.Center) ? TextFormatFlags.HorizontalCenter :
TextFormatFlags.Right);
flags |= TextFormatFlags.WordEllipsis;
DrawText(flags);
}
/// <include file='doc\DrawListViewColumnHeaderEventArgs.uex' path='docs/doc[@for="DrawListViewColumnHeaderEventArgs.DrawText1"]/*' />
/// <devdoc>
/// Draws the header's text (overloaded) - takes a TextFormatFlags argument.
/// </devdoc>
[
SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters") // We want to measure the size of blank space.
// So we don't have to localize it.
]
public void DrawText(TextFormatFlags flags) {
string text = header.Text;
int padding = TextRenderer.MeasureText(" ", font).Width;
Rectangle newBounds = Rectangle.Inflate(bounds, -padding, 0);
TextRenderer.DrawText(graphics, text, font, newBounds, foreColor, flags);
}
}
}
| |
using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using newtelligence.DasBlog.Web.Core;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Runtime.Proxies;
using System.Collections;
namespace newtelligence.DasBlog.Web
{
/// <summary>
/// Summary description for EditNavigatorLinksBox.
/// </summary>
public partial class EditCrosspostSitesBox : SharedBaseControl
{
[TransientPageState]
public CrosspostSiteCollection crosspostSites;
protected System.Web.UI.WebControls.RequiredFieldValidator validatorRFname;
protected System.Web.UI.WebControls.Panel Panel1;
private CrossPostServerInfo[] crossPostServerInfo;
protected System.Resources.ResourceManager resmgr;
private void SaveSites( )
{
SiteConfig siteConfig = SiteConfig.GetSiteConfig(SiteConfig.GetConfigFilePathFromCurrentContext());
siteConfig.CrosspostSites.Clear();
siteConfig.CrosspostSites.AddRange(crosspostSites);
XmlSerializer ser = new XmlSerializer(typeof(SiteConfig));
using (StreamWriter writer = new StreamWriter(SiteConfig.GetConfigFilePathFromCurrentContext()))
{
ser.Serialize(writer, siteConfig);
}
}
protected string TruncateString( string s, int max )
{
if ( s == null )
{
return "";
}
else if ( s.Length < max )
{
return s;
}
else if ( s.Length >= max )
{
return s.Substring(0,max)+"...";
}
return s;
}
private void LoadSites( )
{
SiteConfig siteConfig = SiteConfig.GetSiteConfig(SiteConfig.GetConfigFilePathFromCurrentContext());
crosspostSites = new CrosspostSiteCollection(siteConfig.CrosspostSites);
// luke@jurasource.co.uk 24-MAR-04
// ensure that each allBlogNames property has at
// least one entry, namely the blog name
foreach (CrosspostSite site in crosspostSites)
{
if ( site.AllBlogNames == null || site.AllBlogNames.Length == 0 )
site.AllBlogNames = new string[]{site.BlogName};
}
}
public ICollection GetServerInfo()
{
LoadCrossPostServerInfo();
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Value", typeof(string)));
foreach(CrossPostServerInfo info in crossPostServerInfo)
{
dr = dt.NewRow();
dr[0] = info.Name;
dr[1] = info.Name;
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}
private void LoadCrossPostServerInfo()
{
string fullPath = SiteConfig.GetConfigPathFromCurrentContext() + "CrossPostServerInfo.xml";
if (File.Exists(fullPath))
{
FileStream fileStream = newtelligence.DasBlog.Util.FileUtils.OpenForRead(fullPath);
if ( fileStream != null )
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(CrossPostServerInfo[]));
StreamReader reader = new StreamReader(fileStream);
crossPostServerInfo = (CrossPostServerInfo[])ser.Deserialize(reader);
}
catch(Exception e)
{
ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e);
}
finally
{
fileStream.Close();
}
}
}
else
{
CrossPostServerInfo[] crossPostServerInfo = new CrossPostServerInfo[1];
CrossPostServerInfo c1 = new CrossPostServerInfo();
c1.Name = "DasBlog";
c1.Endpoint = "blogger.aspx";
c1.Port = 80;
c1.Service = 1;
crossPostServerInfo[0] = c1;
}
}
private void BindGrid()
{
crosspostSitesGrid.DataSource = crosspostSites;
crosspostSitesGrid.Columns[0].HeaderText = resmgr.GetString("text_profile");
DataBind();
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (SiteSecurity.IsInRole("admin") == false)
{
Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
}
resmgr = ((System.Resources.ResourceManager)ApplicationResourceTable.Get());
if ( !IsPostBack || crosspostSites == null )
{
LoadSites( );
}
BindGrid();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.crosspostSitesGrid.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.crosspostSitesGrid_ItemCommand);
this.crosspostSitesGrid.CancelCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.crosspostSitesGrid_CancelCommand);
this.crosspostSitesGrid.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.crosspostSitesGrid_EditCommand);
this.crosspostSitesGrid.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.crosspostSitesGrid_UpdateCommand);
this.crosspostSitesGrid.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.crosspostSitesGrid_DeleteCommand);
}
#endregion
private void crosspostSitesGrid_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
crosspostSitesGrid.EditItemIndex = e.Item.ItemIndex;
DataBind();
// luke@jurasource.co.uk
// Ensure the correct item in the blog names ddl is selected
DropDownList allBlogNames = (DropDownList) crosspostSitesGrid.Items[e.Item.ItemIndex].FindControl("listAllBlogNames");
CrosspostSite site = crosspostSites[e.Item.ItemIndex];
// james.snape@gmail.com
// There seems to be an issue with Blogger and accounts with spaces in
// as it sometimes results in two enties in this list split on the space char.
// This ensures the page displays even when the list item is missing.
if (allBlogNames.Items.FindByValue(site.BlogName) != null)
{
allBlogNames.SelectedValue = site.BlogName;
}
}
private void crosspostSitesGrid_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
crosspostSites.RemoveAt(e.Item.DataSetIndex);
crosspostSitesGrid.EditItemIndex = -1;
DataBind();
changesAlert.Visible = true;
}
private void crosspostSitesGrid_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
crosspostSitesGrid.EditItemIndex = -1;
DataBind();
}
private void crosspostSitesGrid_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
CrosspostSite site = crosspostSites[e.Item.DataSetIndex];
site.ProfileName = ((TextBox)e.Item.FindControl("textProfileName")).Text;
site.HostName = ((TextBox)e.Item.FindControl("textHostName")).Text;
site.Port = int.Parse(((TextBox)e.Item.FindControl("textPort")).Text);
site.Endpoint = ((TextBox)e.Item.FindControl("textEndpoint")).Text;
site.Username = ((TextBox)e.Item.FindControl("textUsername")).Text;
site.ApiType = ((DropDownList)e.Item.FindControl("listApiType")).SelectedValue;
TextBox textPassword = ((TextBox)e.Item.FindControl("textPassword"));
if ( textPassword.Text.Length > 0 )
{
site.Password = textPassword.Text;
}
// luke@jurasource.co.uk 24-MAR-04
// Ensure the correct blog is selected from the ddl
DropDownList allBlogNames = (DropDownList) e.Item.FindControl("listAllBlogNames");
if ( allBlogNames != null && allBlogNames.SelectedItem.Text != null )
{
site.BlogName = allBlogNames.SelectedItem.Text;
site.BlogId = ((TextBox)e.Item.FindControl(("textBlogId"))).Text;
}
crosspostSitesGrid.EditItemIndex = -1;
DataBind();
changesAlert.Visible = true;
}
private void crosspostSitesGrid_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
crosspostSitesGrid.CurrentPageIndex = e.NewPageIndex;
DataBind();
}
private void crosspostSitesGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if ( e.CommandName == "AddItem" )
{
CrosspostSite newSite = new CrosspostSite();
newSite.ProfileName = "New Profile";
newSite.Port=80;
// luke@jurasource 24-MAR-04
// init all blog names
newSite.AllBlogNames = new string[]{""};
crosspostSites.Insert(0,newSite);
crosspostSitesGrid.CurrentPageIndex = 0;
crosspostSitesGrid.EditItemIndex = 0;
BindGrid();
}
else if ( e.CommandName == "autoFill" )
{
DropDownList dropDownList = (DropDownList)e.Item.FindControl("blogSoftware");
TextBox textHostName = (TextBox)e.Item.FindControl("textHostName");
TextBox textEndpoint = (TextBox)e.Item.FindControl("textEndpoint");
TextBox textBoxBlogURL = (TextBox)e.Item.FindControl("textBoxBlogURL");
DropDownList dropDownApi = (DropDownList)e.Item.FindControl("listApiType");
string rawBlogUrl = textBoxBlogURL.Text;
rawBlogUrl = rawBlogUrl.Replace("http://", "");
string[] blogUrl = rawBlogUrl.Split('/');
textHostName.Text = blogUrl[0];
string endpoint = "";
for (int index = 1; index < blogUrl.Length; index++)
{
endpoint += "/" + blogUrl[index];
}
CrossPostServerInfo currentInfo = (CrossPostServerInfo)crossPostServerInfo.GetValue(dropDownList.SelectedIndex);
if (endpoint.Length != 0 && endpoint.EndsWith("/") == false)
endpoint += "/";
textEndpoint.Text = endpoint + currentInfo.Endpoint;
dropDownApi.SelectedIndex = currentInfo.Service;
}
else if ( e.CommandName =="testConnection" )
{
Label labelTestError;
labelTestError = ((Label)e.Item.FindControl("labelTestError"));
labelTestError.Text = "";
try
{
TextBox textBlogName;
TextBox textPassword;
CrosspostSite site = crosspostSites[e.Item.DataSetIndex];
site.ProfileName = ((TextBox)e.Item.FindControl("textProfileName")).Text;
site.HostName = ((TextBox)e.Item.FindControl("textHostName")).Text;
site.Port = int.Parse(((TextBox)e.Item.FindControl("textPort")).Text);
site.Endpoint = ((TextBox)e.Item.FindControl("textEndpoint")).Text;
site.Username = ((TextBox)e.Item.FindControl("textUsername")).Text;
site.ApiType = ((DropDownList)e.Item.FindControl("listApiType")).SelectedValue;
textPassword = ((TextBox)e.Item.FindControl("textPassword"));
if ( textPassword.Text.Length > 0 )
{
site.Password = textPassword.Text;
}
textBlogName = ((TextBox)e.Item.FindControl("textBlogName"));
UriBuilder uriBuilder = new UriBuilder("http",site.HostName,site.Port,site.Endpoint);
BloggerAPIClientProxy proxy = new BloggerAPIClientProxy();
proxy.Url = uriBuilder.ToString();
proxy.UserAgent="newtelligence dasBlog/1.4";
bgBlogInfo[] blogInfos = proxy.blogger_getUsersBlogs("",site.Username, site.Password);
if ( blogInfos.Length > 0 )
{
// luke@jurasource.co.uk 24-MAR-04
// refresh all the blog names for this crosspost site
string[] allBlogNames = new string[blogInfos.Length];
for (int blog=0; blog<blogInfos.Length; blog++)
allBlogNames[blog] = blogInfos[blog].blogName;
site.AllBlogNames = allBlogNames;
// Default the crosspost blog to the first one
site.BlogName = textBlogName.Text = blogInfos[0].blogName;
site.BlogId = blogInfos[0].blogid;
}
BindGrid();
}
catch( Exception exc )
{
labelTestError.Text = exc.Message;
}
finally
{
}
}
}
protected void buttonSaveChanges_Click(object sender, System.EventArgs e)
{
SaveSites();
changesAlert.Visible = false;
}
protected void crosspostSitesGrid_Load(object sender, System.EventArgs e)
{
}
}
}
| |
using System;
using Libev;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Manos.IO.Libev
{
class TcpSocket : IPSocket<ByteBuffer, IByteStream>, ITcpSocket, ITcpServerSocket
{
IOWatcher listener;
TcpSocketStream stream;
class TcpSocketStream : EventedByteStream, ISendfileCapable
{
TcpSocket parent;
byte [] receiveBuffer = new byte[4096];
public TcpSocketStream (TcpSocket parent, IntPtr handle)
: base (parent.Context, handle)
{
this.parent = parent;
}
public override long Position {
get { throw new NotSupportedException (); }
set { throw new NotSupportedException (); }
}
public override bool CanRead {
get { return true; }
}
public override bool CanWrite {
get { return true; }
}
public void SendFile (string file)
{
CheckDisposed ();
if (file == null)
throw new ArgumentNullException ("file");
Write (new SendFileOperation (Context, this, file));
}
protected override void Dispose (bool disposing)
{
if (parent != null) {
RaiseEndOfStream ();
receiveBuffer = null;
parent = null;
}
base.Dispose (disposing);
}
public override void Flush ()
{
}
protected override void HandleRead ()
{
int err;
var received = SocketFunctions.manos_socket_receive (Handle.ToInt32 (), receiveBuffer,
receiveBuffer.Length, out err);
if (received < 0 && err != 0 || received == 0) {
if (received < 0) {
RaiseError (Errors.SocketStreamFailure ("Read failure", err));
}
Close ();
} else {
byte [] newBuffer = new byte [received];
Buffer.BlockCopy (receiveBuffer, 0, newBuffer, 0, received);
RaiseData (new ByteBuffer (newBuffer));
}
}
protected override WriteResult WriteSingleFragment (ByteBuffer buffer)
{
int err;
int sent = SocketFunctions.manos_socket_send (Handle.ToInt32 (), buffer.Bytes, buffer.Position,
buffer.Length, out err);
if (sent < 0 && err != 0) {
RaiseError (Errors.SocketStreamFailure ("Write failure", err));
return WriteResult.Error;
} else {
buffer.Skip (sent);
return buffer.Length == 0 ? WriteResult.Consume : WriteResult.Continue;
}
}
}
public TcpSocket (Context context, AddressFamily addressFamily)
: base (context, addressFamily, ProtocolFamily.Tcp)
{
}
TcpSocket (Context context, AddressFamily addressFamily, int fd, IPEndPoint local, IPEndPoint remote)
: base (context, addressFamily, fd)
{
this.stream = new TcpSocketStream (this, new IntPtr (fd));
this.localname = local;
this.peername = remote;
this.IsConnected = true;
this.IsBound = true;
}
public override IByteStream GetSocketStream ()
{
CheckDisposed ();
if (!IsConnected)
throw new SocketException ("Not conntected", SocketError.NotConnected);
if (listener != null)
throw new InvalidOperationException ();
if (stream == null) {
stream = new TcpSocketStream (this, new IntPtr (fd));
}
return stream;
}
public void Listen (int backlog, Action<ITcpSocket> callback)
{
CheckDisposed ();
if (stream != null)
throw new InvalidOperationException ();
if (listener != null) {
listener.Stop ();
listener.Dispose ();
}
int error;
var result = SocketFunctions.manos_socket_listen (fd, backlog, out error);
if (result < 0) {
throw Errors.SocketFailure ("Listen failure", error);
}
listener = new IOWatcher (new IntPtr (fd), EventTypes.Read, Context.Loop, delegate {
ManosIPEndpoint ep;
var client = SocketFunctions.manos_socket_accept (fd, out ep, out error);
if (client < 0 && error != 0) {
throw new Exception (string.Format ("Error while accepting: {0}", Errors.ErrorToString (error)));
} else if (client > 0) {
var socket = new TcpSocket (Context, AddressFamily, client, LocalEndpoint, ep);
callback (socket);
}
});
listener.Start ();
}
protected override void Dispose(bool disposing)
{
if (listener != null) {
listener.Stop ();
listener.Dispose ();
listener = null;
}
if (stream != null) {
stream.Close ();
stream = null;
}
base.Dispose(disposing);
}
public override void Connect (IPEndPoint endpoint, Action callback, Action<Exception> error)
{
CheckDisposed ();
if (endpoint == null)
throw new ArgumentNullException ("endpoint");
if (callback == null)
throw new ArgumentNullException ("callback");
if (error == null)
throw new ArgumentNullException ("error");
if (localname != null && localname.AddressFamily != endpoint.AddressFamily)
throw new ArgumentException ();
if (IsConnected)
throw new InvalidOperationException ();
int err;
ManosIPEndpoint ep = endpoint;
err = SocketFunctions.manos_socket_connect_ip (fd, ref ep, out err);
if (err != 0) {
throw Errors.SocketFailure ("Connect failure", err);
} else {
var connectWatcher = new IOWatcher (new IntPtr (fd), EventTypes.Write, Context.Loop, (watcher, revents) => {
watcher.Stop ();
watcher.Dispose ();
var result = SocketFunctions.manos_socket_peername_ip (fd, out ep, out err);
if (result < 0) {
error (Errors.SocketFailure ("Connect failure", err));
} else {
peername = endpoint;
IsConnected = true;
callback ();
}
});
connectWatcher.Start ();
}
}
}
}
| |
// ==++==
//
//
// Copyright (c) 2006 Microsoft Corporation. All rights reserved.
//
// The use and distribution terms for this software are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
//
// ==--==
namespace Microsoft.JScript{
using Microsoft.JScript.Vsa;
using System;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Resources;
using System.Security.Permissions;
using System.Globalization;
using Microsoft.Vsa;
using System.Text;
//-------------------------------------------------------------------------------------------------------
// JScriptException
//
// An error in JScript goes to a CLR host/program in the form of a JScriptException. However a
// JScriptException is not always thrown. In fact a JScriptException is also a IVsaError and thus it can be
// passed to the host through IVsaSite.OnCompilerError(IVsaError error).
// When a JScriptException is not a wrapper for some other object (usually either a COM+ exception or
// any value thrown in a JScript throw statement) it takes a JSError value.
// The JSError enum is defined in JSError.cs. When introducing a new type of error perform
// the following four steps:
// 1- Add the error in the JSError enum (JSError.cs)
// 2- Update GetErrorType() to return a value from the ErrorType enum (in ErrorConstructor) for the
// error you just defined. GetErrorType() is a map form JSError to a JScript object in the Error
// hierarchy
// 3- Update Microsoft.JScript.txt with the US English error message
// 4- Update Severity.
//-------------------------------------------------------------------------------------------------------
[Serializable] public class JScriptException : ApplicationException, IVsaFullErrorInfo{
internal Object value;
[NonSerialized] internal Context context;
internal bool isError;
internal static readonly String ContextStringDelimiter = ";;";
private int code; // This is same as base.HResult. We have this so that the debuugger can get the
// error code without doing a func-eval ( to evaluate the HResult property )
// We don't expect this to be called usually, but add it in case of serialization.
public JScriptException()
:this(JSError.NoError){
}
public JScriptException(string m)
:this(m, null){
}
public JScriptException(string m, Exception e)
:this(m, e, null){
}
public JScriptException(JSError errorNumber)
:this(errorNumber, null){
}
internal JScriptException(JSError errorNumber, Context context){
this.value = Missing.Value;
this.context = context;
this.code = this.HResult = unchecked((int)(0x800A0000 + (int)errorNumber));
}
internal JScriptException(Object value, Context context){
this.value = value;
this.context = context;
this.code = this.HResult = unchecked((int)(0x800A0000 + (int)JSError.UncaughtException));
}
internal JScriptException(Exception e, Context context) : this(null, e, context){
}
internal JScriptException(string m, Exception e, Context context) : base(m, e){
this.value = e;
this.context = context;
if (e is StackOverflowException){
this.code = this.HResult = unchecked((int)(0x800A0000 + (int)JSError.OutOfStack));
this.value = Missing.Value;
}else if (e is OutOfMemoryException){
this.code = this.HResult = unchecked((int)(0x800A0000 + (int)JSError.OutOfMemory));
this.value = Missing.Value;
}
else {
int hr = System.Runtime.InteropServices.Marshal.GetHRForException(e);
if ((hr & 0xffff0000) == 0x800A0000 && System.Enum.IsDefined(typeof(JSError), hr & 0xffff)){
this.code = this.HResult = hr;
this.value = Missing.Value;
}else
this.code = this.HResult = unchecked((int)(0x800A0000 + (int)JSError.UncaughtException));
}
}
protected JScriptException(SerializationInfo info, StreamingContext context)
: base(info, context){
this.code = this.HResult = info.GetInt32("Code");
this.value = Missing.Value;
this.isError = info.GetBoolean("IsError");
}
public String SourceMoniker{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
if (this.context != null)
return this.context.document.documentName;
else
return "no source";
}
}
public int StartColumn{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
return this.Column;
}
}
public int Column{
get{
if (this.context != null)
return this.context.StartColumn + this.context.document.startCol + 1;
else
return 0;
}
}
// We have this method simply to have the same link demand on it as the interface
// method has and avoid a FXCOP warning. The Description property itself cannot have
// a link demand on it since it is used by the JScript Error object's Description property
string IVsaError.Description{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
return this.Description;
}
}
public string Description{
get{
return this.Message;
}
}
public int EndLine{
get{
if (this.context != null)
return this.context.EndLine + this.context.document.startLine - this.context.document.lastLineInSource;
else
return 0;
}
}
public int EndColumn{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
if (this.context != null)
return this.context.EndColumn + this.context.document.startCol + 1;
else
return 0;
}
}
// We have this method simply to have the same link demand on it as the interface
// method has and avoid a FXCOP warning. The Number property itself cannot have
// a link demand on it since it is used by the JScript Error object's Number property
int IVsaError.Number{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
return this.Number;
}
}
public int Number{
get{
return this.ErrorNumber;
}
}
public int ErrorNumber{
get{
return this.HResult;
}
}
internal ErrorType GetErrorType(){
int ec = this.HResult;
if ((ec & 0xFFFF0000) != 0x800A0000) return ErrorType.OtherError;
switch ((JSError)(ec & 0xFFFF)){
case JSError.AbstractWithBody : return ErrorType.SyntaxError;
case JSError.AmbiguousConstructorCall : return ErrorType.ReferenceError;
case JSError.AmbiguousMatch : return ErrorType.ReferenceError;
case JSError.ArrayLengthConstructIncorrect : return ErrorType.RangeError;
case JSError.ArrayLengthAssignIncorrect : return ErrorType.RangeError;
case JSError.AssemblyAttributesMustBeGlobal : return ErrorType.SyntaxError;
case JSError.AssignmentToReadOnly : return ErrorType.ReferenceError;
case JSError.BadBreak : return ErrorType.SyntaxError;
case JSError.BadContinue : return ErrorType.SyntaxError;
case JSError.BadHexDigit : return ErrorType.SyntaxError;
case JSError.BadLabel : return ErrorType.SyntaxError;
case JSError.BadReturn : return ErrorType.SyntaxError;
case JSError.BadSwitch : return ErrorType.SyntaxError;
case JSError.BadFunctionDeclaration : return ErrorType.SyntaxError;
case JSError.BadPropertyDeclaration : return ErrorType.SyntaxError;
case JSError.BadVariableDeclaration : return ErrorType.SyntaxError;
case JSError.BooleanExpected : return ErrorType.TypeError;
case JSError.CannotInstantiateAbstractClass : return ErrorType.TypeError;
case JSError.CannotNestPositionDirective : return ErrorType.SyntaxError;
case JSError.CannotReturnValueFromVoidFunction : return ErrorType.TypeError;
case JSError.CantAssignThis : return ErrorType.ReferenceError;
case JSError.CcInvalidElif : return ErrorType.SyntaxError;
case JSError.CcInvalidElse : return ErrorType.SyntaxError;
case JSError.CcInvalidEnd : return ErrorType.SyntaxError;
case JSError.CcOff : return ErrorType.SyntaxError;
case JSError.CircularDefinition : return ErrorType.SyntaxError;
case JSError.ClashWithProperty : return ErrorType.SyntaxError;
case JSError.ClassNotAllowed : return ErrorType.SyntaxError;
case JSError.ConstructorMayNotHaveReturnType : return ErrorType.SyntaxError;
case JSError.DateExpected : return ErrorType.TypeError;
case JSError.DifferentReturnTypeFromBase : return ErrorType.TypeError;
case JSError.DoesNotHaveAnAddress : return ErrorType.ReferenceError;
case JSError.DupDefault : return ErrorType.SyntaxError;
case JSError.DuplicateMethod : return ErrorType.TypeError;
case JSError.DuplicateNamedParameter : return ErrorType.ReferenceError;
case JSError.EnumeratorExpected : return ErrorType.TypeError;
case JSError.ErrEOF : return ErrorType.SyntaxError;
case JSError.ExpectedAssembly: return ErrorType.SyntaxError;
case JSError.ExpressionExpected : return ErrorType.SyntaxError;
case JSError.FractionOutOfRange : return ErrorType.RangeError;
case JSError.FunctionExpected : return ErrorType.TypeError;
case JSError.IllegalAssignment : return ErrorType.ReferenceError;
case JSError.IllegalChar : return ErrorType.SyntaxError;
case JSError.IllegalEval : return ErrorType.EvalError;
case JSError.ImpossibleConversion : return ErrorType.TypeError;
case JSError.InstanceNotAccessibleFromStatic : return ErrorType.ReferenceError;
case JSError.InvalidBaseTypeForEnum : return ErrorType.TypeError;
case JSError.InvalidCall : return ErrorType.TypeError;
case JSError.InvalidCustomAttribute : return ErrorType.TypeError;
case JSError.InvalidCustomAttributeArgument : return ErrorType.TypeError;
case JSError.InvalidCustomAttributeClassOrCtor : return ErrorType.TypeError;
case JSError.InvalidDebugDirective: return ErrorType.SyntaxError;
case JSError.InvalidElse : return ErrorType.SyntaxError;
case JSError.InvalidPositionDirective: return ErrorType.SyntaxError;
case JSError.InvalidPrototype : return ErrorType.TypeError;
case JSError.ItemNotAllowedOnExpandoClass : return ErrorType.SyntaxError;
case JSError.KeywordUsedAsIdentifier : return ErrorType.SyntaxError;
case JSError.MemberInitializerCannotContainFuncExpr : return ErrorType.SyntaxError;
case JSError.MissingConstructForAttributes : return ErrorType.SyntaxError;
case JSError.MissingNameParameter : return ErrorType.ReferenceError;
case JSError.MoreNamedParametersThanArguments : return ErrorType.ReferenceError;
case JSError.MustBeEOL : return ErrorType.SyntaxError;
case JSError.MustProvideNameForNamedParameter : return ErrorType.ReferenceError;
case JSError.IncorrectNumberOfIndices : return ErrorType.ReferenceError;
case JSError.NeedArrayObject : return ErrorType.TypeError;
case JSError.NeedCompileTimeConstant : return ErrorType.ReferenceError;
case JSError.NeedInterface : return ErrorType.TypeError;
case JSError.NeedInstance : return ErrorType.ReferenceError;
case JSError.NeedType : return ErrorType.TypeError;
case JSError.NestedInstanceTypeCannotBeExtendedByStatic : return ErrorType.ReferenceError;
case JSError.NoAt : return ErrorType.SyntaxError;
case JSError.NoCatch : return ErrorType.SyntaxError;
case JSError.NoCcEnd : return ErrorType.SyntaxError;
case JSError.NoColon : return ErrorType.SyntaxError;
case JSError.NoComma : return ErrorType.SyntaxError;
case JSError.NoCommaOrTypeDefinitionError : return ErrorType.SyntaxError;
case JSError.NoCommentEnd : return ErrorType.SyntaxError;
case JSError.NoConstructor : return ErrorType.TypeError;
case JSError.NoEqual : return ErrorType.SyntaxError;
case JSError.NoIdentifier : return ErrorType.SyntaxError;
case JSError.NoLabel : return ErrorType.SyntaxError;
case JSError.NoLeftParen : return ErrorType.SyntaxError;
case JSError.NoLeftCurly : return ErrorType.SyntaxError;
case JSError.NoMemberIdentifier : return ErrorType.SyntaxError;
case JSError.NonStaticWithTypeName : return ErrorType.ReferenceError;
case JSError.NoRightBracket : return ErrorType.SyntaxError;
case JSError.NoRightBracketOrComma : return ErrorType.SyntaxError;
case JSError.NoRightCurly : return ErrorType.SyntaxError;
case JSError.NoRightParen : return ErrorType.SyntaxError;
case JSError.NoRightParenOrComma : return ErrorType.SyntaxError;
case JSError.NoSemicolon : return ErrorType.SyntaxError;
case JSError.NoSuchMember : return ErrorType.ReferenceError;
case JSError.NoSuchStaticMember : return ErrorType.ReferenceError;
case JSError.NotIndexable : return ErrorType.TypeError;
case JSError.NotAccessible : return ErrorType.ReferenceError;
case JSError.NotAnExpandoFunction : return ErrorType.ReferenceError;
case JSError.NotCollection : return ErrorType.TypeError;
case JSError.NotConst : return ErrorType.SyntaxError;
case JSError.NotInsideClass : return ErrorType.SyntaxError;
case JSError.NoWhile : return ErrorType.SyntaxError;
case JSError.NumberExpected : return ErrorType.TypeError;
case JSError.ObjectExpected : return ErrorType.TypeError;
case JSError.OLENoPropOrMethod : return ErrorType.TypeError;
case JSError.OnlyClassesAllowed : return ErrorType.SyntaxError;
case JSError.OnlyClassesAndPackagesAllowed : return ErrorType.SyntaxError;
case JSError.PackageExpected : return ErrorType.SyntaxError;
case JSError.ParamListNotLast : return ErrorType.SyntaxError;
case JSError.PrecisionOutOfRange : return ErrorType.RangeError;
case JSError.PropertyLevelAttributesMustBeOnGetter : return ErrorType.ReferenceError;
case JSError.RegExpExpected : return ErrorType.TypeError;
case JSError.RegExpSyntax : return ErrorType.SyntaxError;
case JSError.ShouldBeAbstract : return ErrorType.SyntaxError;
case JSError.StaticMissingInStaticInit : return ErrorType.SyntaxError;
case JSError.StaticRequiresTypeName : return ErrorType.ReferenceError;
case JSError.StringExpected : return ErrorType.TypeError;
case JSError.SuperClassConstructorNotAccessible : return ErrorType.ReferenceError;
case JSError.SyntaxError : return ErrorType.SyntaxError;
case JSError.TooFewParameters : return ErrorType.TypeError;
case JSError.TooManyTokensSkipped : return ErrorType.SyntaxError;
case JSError.TypeCannotBeExtended : return ErrorType.ReferenceError;
case JSError.TypeMismatch : return ErrorType.TypeError;
case JSError.UndeclaredVariable : return ErrorType.ReferenceError;
case JSError.UndefinedIdentifier : return ErrorType.ReferenceError;
case JSError.UnexpectedSemicolon : return ErrorType.SyntaxError;
case JSError.UnreachableCatch : return ErrorType.SyntaxError;
case JSError.UnterminatedString : return ErrorType.SyntaxError;
case JSError.URIEncodeError : return ErrorType.URIError;
case JSError.URIDecodeError : return ErrorType.URIError;
case JSError.VBArrayExpected : return ErrorType.TypeError;
case JSError.WriteOnlyProperty : return ErrorType.ReferenceError;
case JSError.WrongDirective : return ErrorType.SyntaxError;
case JSError.BadModifierInInterface : return ErrorType.SyntaxError;
case JSError.VarIllegalInInterface : return ErrorType.SyntaxError;
case JSError.InterfaceIllegalInInterface : return ErrorType.SyntaxError;
case JSError.NoVarInEnum : return ErrorType.SyntaxError;
case JSError.EnumNotAllowed: return ErrorType.SyntaxError;
case JSError.PackageInWrongContext: return ErrorType.SyntaxError;
case JSError.CcInvalidInDebugger: return ErrorType.SyntaxError;
case JSError.TypeNameTooLong: return ErrorType.SyntaxError;
}
return ErrorType.OtherError;
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter=true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) throw new ArgumentNullException("info");
base.GetObjectData(info, context);
info.AddValue("IsError", this.isError);
info.AddValue("Code", this.code);
}
public int Line{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
if (this.context != null)
return this.context.StartLine + this.context.document.startLine - this.context.document.lastLineInSource;
else
return 0;
}
}
public String LineText{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
if (this.context != null)
return this.context.source_string;
else
return "";
}
}
internal static String Localize(String key, CultureInfo culture){
return JScriptException.Localize(key, null, culture);
}
internal static String Localize(String key, String context, CultureInfo culture){
try{
ResourceManager rm = new ResourceManager("DodoNet.JScript.engine.microsoft.jscript", typeof(JScriptException).Module.Assembly);
String localizedString = rm.GetString(key, culture);
if (localizedString != null){
// locate context/no-context string delimiter
int splitAt = localizedString.IndexOf(ContextStringDelimiter);
if (splitAt == -1){
// there is no context-specific string
return localizedString;
}else if (context == null){
// splitAt is one character past the end of the no-context string
return localizedString.Substring(0, splitAt);
}else{
// splitAt is two characters before the beginning of the context string
return String.Format(culture, localizedString.Substring(splitAt+2), context);
}
}
}catch(MissingManifestResourceException){
}
return key;
}
public override String Message{
get{
if (this.value is Exception){
Exception e = (Exception)this.value;
String result = e.Message;
if (result != null && result.Length > 0)
return result;
else{
return e.ToString();
}
}
String code = (this.HResult & 0xFFFF).ToString(CultureInfo.InvariantCulture);
CultureInfo culture = null;
if (this.context != null && this.context.document != null){
VsaEngine engine = this.context.document.engine;
if (engine != null)
culture = engine.ErrorCultureInfo;
}
if (this.value is ErrorObject){
String result = ((ErrorObject)this.value).Message;
if (result != null && result.Length > 0)
return result;
else
return Localize("No description available", culture) + ": " + code;
}else if (this.value is String){
switch (((JSError)(this.HResult & 0xFFFF))){
case JSError.CannotBeAbstract :
case JSError.Deprecated:
case JSError.DifferentReturnTypeFromBase :
case JSError.DuplicateName :
case JSError.HidesAbstractInBase:
case JSError.HidesParentMember :
case JSError.InvalidCustomAttributeTarget :
case JSError.ImplicitlyReferencedAssemblyNotFound :
case JSError.MustImplementMethod :
case JSError.NoSuchMember :
case JSError.NoSuchType :
case JSError.NoSuchStaticMember :
case JSError.NotIndexable :
case JSError.TypeCannotBeExtended :
case JSError.TypeMismatch :
case JSError.InvalidResource:
case JSError.IncompatibleAssemblyReference:
case JSError.InvalidAssemblyKeyFile:
case JSError.TypeNameTooLong:
return Localize(code, (String)this.value, culture);
default : return (String)this.value;
}
}
// special case some errors with contextual information
if (this.context != null){
switch (((JSError)(this.HResult & 0xFFFF))){
case JSError.AmbiguousBindingBecauseOfWith :
case JSError.AmbiguousBindingBecauseOfEval :
case JSError.AssignmentToReadOnly :
case JSError.DuplicateName :
case JSError.InstanceNotAccessibleFromStatic :
case JSError.KeywordUsedAsIdentifier :
case JSError.NeedInstance :
case JSError.NonStaticWithTypeName :
case JSError.NotAccessible :
case JSError.NotDeletable :
case JSError.NotMeantToBeCalledDirectly :
case JSError.ObjectExpected :
case JSError.StaticRequiresTypeName :
case JSError.UndeclaredVariable :
case JSError.UndefinedIdentifier :
case JSError.VariableLeftUninitialized :
case JSError.VariableMightBeUnitialized :
return Localize(code, this.context.GetCode(), culture);
}
}
return Localize(((int)(this.HResult & 0xFFFF)).ToString(CultureInfo.InvariantCulture), culture);
}
}
public int Severity{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
//guide: 0 == there will be a run-time error if this code executes
// 1 == the programmer probably did not intend to do this
// 2 == this can lead to problems in the future.
// 3 == this can lead to performance problems
// 4 == this is just not right.
int ec = this.HResult;
if ((ec & 0xFFFF0000) != 0x800A0000) return 0;
if (!this.isError){
switch ((JSError)(ec & 0xFFFF)){
case JSError.AmbiguousBindingBecauseOfWith : return 4;
case JSError.AmbiguousBindingBecauseOfEval : return 4;
case JSError.ArrayMayBeCopied : return 1;
case JSError.AssignmentToReadOnly : return 1;
case JSError.BadOctalLiteral : return 1;
case JSError.BadWayToLeaveFinally : return 3;
case JSError.BaseClassIsExpandoAlready : return 1;
case JSError.Deprecated : return 2;
case JSError.DifferentReturnTypeFromBase : return 1;
case JSError.DuplicateName : return 1;
case JSError.DupVisibility : return 1;
case JSError.GetAndSetAreInconsistent : return 1;
case JSError.HidesParentMember : return 1;
case JSError.IncompatibleVisibility : return 1;
case JSError.KeywordUsedAsIdentifier : return 2;
case JSError.NewNotSpecifiedInMethodDeclaration : return 1;
case JSError.NotDeletable : return 1;
case JSError.NotMeantToBeCalledDirectly : return 1;
case JSError.OctalLiteralsAreDeprecated : return 2;
case JSError.PossibleBadConversion : return 1;
case JSError.PossibleBadConversionFromString : return 4;
case JSError.ShouldBeAbstract : return 1;
case JSError.StringConcatIsSlow : return 3;
case JSError.SuspectAssignment : return 1;
case JSError.SuspectLoopCondition : return 1;
case JSError.SuspectSemicolon : return 1;
case JSError.TooFewParameters : return 1;
case JSError.TooManyParameters : return 1;
case JSError.UndeclaredVariable : return 3;
case JSError.UselessAssignment : return 1;
case JSError.UselessExpression : return 1;
case JSError.VariableLeftUninitialized : return 3;
case JSError.VariableMightBeUnitialized : return 3;
case JSError.IncompatibleAssemblyReference : return 1;
}
}
return 0;
}
}
public IVsaItem SourceItem{
[PermissionSetAttribute(SecurityAction.LinkDemand, Name = "FullTrust")]
get{
if (this.context != null)
return this.context.document.sourceItem;
else
throw new NoContextException();
}
}
public override String StackTrace{
get{
if (this.context == null)
return this.Message+Environment.NewLine+base.StackTrace;
StringBuilder result = new StringBuilder();
Context c = this.context;
// Append the "filename: line number" error string
String fileName = c.document.documentName;
if (fileName != null && fileName.Length > 0)
result.Append(fileName+": ");
CultureInfo culture = null;
if (this.context != null && this.context.document != null){
VsaEngine engine = this.context.document.engine;
if (engine != null)
culture = engine.ErrorCultureInfo;
}
result.Append(Localize("Line", culture));
result.Append(' ');
result.Append(c.StartLine);
// report the error
result.Append(" - ");
result.Append(Localize("Error", culture));
result.Append(": ");
result.Append(this.Message);
result.Append(Environment.NewLine);
if (c.document.engine != null){
// Append the stack trace
Stack callContextStack = c.document.engine.Globals.CallContextStack;
for (int i = 0, n = callContextStack.Size(); i < n; i++){
CallContext cctx = (CallContext)callContextStack.Peek(i);
result.Append(" ");
result.Append(Localize("at call to", culture));
result.Append(cctx.FunctionName());
result.Append(' ');
result.Append(Localize("in line", culture));
result.Append(": ");
result.Append(cctx.sourceContext.EndLine);
}
}
return result.ToString();
}
}
}
[Serializable]
public class NoContextException : ApplicationException{
public NoContextException() : base(JScriptException.Localize("No Source Context available", CultureInfo.CurrentUICulture)){
}
public NoContextException(string m) : base(m) {
}
public NoContextException(string m, Exception e) : base(m, e) {
}
protected NoContextException(SerializationInfo s, StreamingContext c) : base(s, c) {
}
}
}
| |
/* Distributed as part of TiledSharp, Copyright 2012 Marshall Ward
* Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
namespace TiledSharp
{
// TODO: The design here is all wrong. A Tileset should be a list of tiles,
// it shouldn't force the user to do so much tile ID management
public class TmxTileset : TmxDocument, ITmxElement
{
public int FirstGid {get; private set;}
public string Name {get; private set;}
public int TileWidth {get; private set;}
public int TileHeight {get; private set;}
public int Spacing {get; private set;}
public int Margin {get; private set;}
public List<TmxTilesetTile> Tiles {get; private set;}
public TmxTileOffset TileOffset {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxImage Image {get; private set;}
public TmxList<TmxTerrain> Terrains {get; private set;}
// TSX file constructor
public TmxTileset(XDocument xDoc, string tmxDir) :
this(xDoc.Element("tileset"), tmxDir) { }
// TMX tileset element constructor
public TmxTileset(XElement xTileset, string tmxDir = "")
{
var xFirstGid = xTileset.Attribute("firstgid");
var source = (string) xTileset.Attribute("source");
if (source != null)
{
// Prepend the parent TMX directory if necessary
source = Path.Combine(tmxDir, source);
// source is always preceded by firstgid
FirstGid = (int) xFirstGid;
// Everything else is in the TSX file
var xDocTileset = ReadXml(source);
var ts = new TmxTileset(xDocTileset, TmxDirectory);
Name = ts.Name;
TileWidth = ts.TileWidth;
TileHeight = ts.TileHeight;
Spacing = ts.Spacing;
Margin = ts.Margin;
TileOffset = ts.TileOffset;
Image = ts.Image;
Terrains = ts.Terrains;
Tiles = ts.Tiles;
Properties = ts.Properties;
}
else
{
// firstgid is always in TMX, but not TSX
if (xFirstGid != null)
FirstGid = (int) xFirstGid;
Name = (string) xTileset.Attribute("name");
TileWidth = (int) xTileset.Attribute("tilewidth");
TileHeight = (int) xTileset.Attribute("tileheight");
Spacing = (int?) xTileset.Attribute("spacing") ?? 0;
Margin = (int?) xTileset.Attribute("margin") ?? 0;
TileOffset = new TmxTileOffset(xTileset.Element("tileoffset"));
Image = new TmxImage(xTileset.Element("image"), tmxDir);
Terrains = new TmxList<TmxTerrain>();
var xTerrainType = xTileset.Element("terraintypes");
if (xTerrainType != null) {
foreach (var e in xTerrainType.Elements("terrain"))
Terrains.Add(new TmxTerrain(e));
}
Tiles = new List<TmxTilesetTile>();
foreach (var xTile in xTileset.Elements("tile"))
{
var tile = new TmxTilesetTile(xTile, Terrains, tmxDir);
Tiles.Add(tile);
}
Properties = new PropertyDict(xTileset.Element("properties"));
}
}
}
public class TmxTileOffset
{
public int X {get; private set;}
public int Y {get; private set;}
public TmxTileOffset(XElement xTileOffset)
{
if (xTileOffset == null) {
X = 0;
Y = 0;
} else {
X = (int)xTileOffset.Attribute("x");
Y = (int)xTileOffset.Attribute("y");
}
}
}
public class TmxTerrain : ITmxElement
{
public string Name {get; private set;}
public int Tile {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxTerrain(XElement xTerrain)
{
Name = (string)xTerrain.Attribute("name");
Tile = (int)xTerrain.Attribute("tile");
Properties = new PropertyDict(xTerrain.Element("properties"));
}
}
public class TmxTilesetTile
{
public int Id {get; private set;}
public List<TmxTerrain> TerrainEdges {get; private set;}
public double Probability {get; private set;}
public PropertyDict Properties {get; private set;}
public TmxImage Image {get; private set;}
public TmxList<TmxObjectGroup> ObjectGroups {get; private set;}
public List<TmxAnimationFrame> AnimationFrames {get; private set;}
// Human-readable aliases to the Terrain markers
public TmxTerrain TopLeft {
get { return TerrainEdges[0]; }
}
public TmxTerrain TopRight {
get { return TerrainEdges[1]; }
}
public TmxTerrain BottomLeft {
get { return TerrainEdges[2]; }
}
public TmxTerrain BottomRight {
get { return TerrainEdges[3]; }
}
public TmxTilesetTile(XElement xTile, TmxList<TmxTerrain> Terrains,
string tmxDir = "")
{
Id = (int)xTile.Attribute("id");
TerrainEdges = new List<TmxTerrain>(4);
int result;
TmxTerrain edge;
var strTerrain = (string)xTile.Attribute("terrain") ?? ",,,";
foreach (var v in strTerrain.Split(',')) {
var success = int.TryParse(v, out result);
if (success)
edge = Terrains[result];
else
edge = null;
TerrainEdges.Add(edge);
}
Probability = (double?)xTile.Attribute("probability") ?? 1.0;
Image = new TmxImage(xTile.Element("image"), tmxDir);
ObjectGroups = new TmxList<TmxObjectGroup>();
foreach (var e in xTile.Elements("objectgroup"))
ObjectGroups.Add(new TmxObjectGroup(e));
AnimationFrames = new List<TmxAnimationFrame>();
if (xTile.Element("animation") != null) {
foreach (var e in xTile.Element("animation").Elements("frame"))
AnimationFrames.Add(new TmxAnimationFrame(e));
}
Properties = new PropertyDict(xTile.Element("properties"));
}
}
public class TmxAnimationFrame
{
public int Id {get; private set;}
public int Duration {get; private set;}
public TmxAnimationFrame(XElement xFrame)
{
Id = (int)xFrame.Attribute("tileid");
Duration = (int)xFrame.Attribute("duration");
}
}
}
| |
// Copyright 2013, Catlike Coding, http://catlikecoding.com
using UnityEditor;
using UnityEngine;
using System.IO;
namespace CatlikeCoding.NumberFlow.Editor {
[CanEditMultipleObjects, CustomEditor(typeof(Diagram))]
public sealed class DiagramEditor : UnityEditor.Editor {
private static GUIContent
tileHorizontallyLabel = new GUIContent("Horizontally"),
tileVerticallyLabel = new GUIContent("Vertically"),
animatePreviewInputLabel = new GUIContent("Input Name"),
cubemapPreviewDirectionLabel = new GUIContent("Preview Direction"),
cubemapPreviewTypeLabel = new GUIContent("Preview Type"),
exportAnimationLoopLabel = new GUIContent("Loop"),
exportAnimationFramesLabel = new GUIContent("Frames"),
exportAnimationFromLabel = new GUIContent("From"),
exportAnimationToLabel = new GUIContent("To"),
exportAnimationInputLabel = new GUIContent("Input Name");
private SerializedObject diagramSO;
private SerializedProperty
libraries, width, height, exportWidth, exportHeight, tileH, tileV, isCubemap, cubemapDirection, cubemapType,
animate, animateName, exportAnimation, exportAnimationLoop, exportAnimationFrames, exportFrom, exportTo,
exportAnimationInput, derivativeScale;
private Diagram diagram;
private string exportFilePath;
private int exportRowIndex = -1, exportFrame;
private Color[] exportPixels;
bool exporting;
CubemapFace exportDirection;
Texture2D exportCubemapTexture;
void OnEnable () {
diagram = target as Diagram;
diagramSO = new SerializedObject(targets);
libraries = diagramSO.FindProperty("functionLibraries");
width = diagramSO.FindProperty("width");
height = diagramSO.FindProperty("height");
exportWidth = diagramSO.FindProperty("exportWidth");
exportHeight = diagramSO.FindProperty("exportHeight");
tileH = diagramSO.FindProperty("tilePreviewHorizontally");
tileV = diagramSO.FindProperty("tilePreviewVertically");
isCubemap = diagramSO.FindProperty("isCubemap");
cubemapDirection = diagramSO.FindProperty("previewCubemapDirection");
cubemapType = diagramSO.FindProperty("previewCubemapType");
animate = diagramSO.FindProperty("animatePreview");
animateName = diagramSO.FindProperty("animatePreviewInput");
exportAnimation = diagramSO.FindProperty("exportAnimation");
exportAnimationLoop = diagramSO.FindProperty("exportAnimationLoop");
exportAnimationFrames = diagramSO.FindProperty("exportAnimationFrames");
exportFrom = diagramSO.FindProperty("exportAnimateFrom");
exportTo = diagramSO.FindProperty("exportAnimateTo");
exportAnimationInput = diagramSO.FindProperty("exportAnimationInput");
derivativeScale = diagramSO.FindProperty("derivativeScale");
}
void OnDisable () {
if (exportRowIndex >= 0) {
EditorUtility.ClearProgressBar();
Debug.LogWarning("Canceled export.");
}
}
public override void OnInspectorGUI () {
diagramSO.Update();
EditorGUILayout.PropertyField(isCubemap);
if (isCubemap.boolValue) {
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(cubemapDirection, cubemapPreviewDirectionLabel);
EditorGUILayout.PropertyField(cubemapType, cubemapPreviewTypeLabel);
EditorGUI.indentLevel -= 1;
}
EditorGUILayout.PropertyField(derivativeScale);
GUILayout.Label("Preview and Default Texture Size");
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(width);
EditorGUILayout.PropertyField(height);
EditorGUI.indentLevel -= 1;
GUILayout.Label("Preview Tiling");
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(tileH, tileHorizontallyLabel);
EditorGUILayout.PropertyField(tileV, tileVerticallyLabel);
EditorGUI.indentLevel -= 1;
EditorGUILayout.PropertyField(animate);
if (animate.boolValue) {
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(animateName, animatePreviewInputLabel);
EditorGUI.indentLevel -= 1;
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(libraries, true);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(exportWidth);
EditorGUILayout.PropertyField(exportHeight);
EditorGUILayout.PropertyField(exportAnimation);
if (exportAnimation.boolValue) {
EditorGUI.indentLevel += 1;
EditorGUILayout.PropertyField(exportAnimationFrames, exportAnimationFramesLabel);
EditorGUILayout.PropertyField(exportAnimationLoop, exportAnimationLoopLabel);
EditorGUILayout.PropertyField(exportAnimationInput, exportAnimationInputLabel);
EditorGUILayout.PropertyField(exportFrom, exportAnimationFromLabel);
EditorGUILayout.PropertyField(exportTo, exportAnimationToLabel);
EditorGUI.indentLevel -= 1;
}
if (targets.Length == 1) {
DoExport();
}
EditorGUILayout.Space();
if (GUILayout.Button("Open Editor")) {
EditorWindow.GetWindow<DiagramWindow>(false, "NumberFlow");
}
if (diagramSO.ApplyModifiedProperties()) {
for (int i = 0; i < targets.Length; i++) {
(targets[i] as Diagram).prepared = false;
}
}
}
private int exportOutputIndex = -1;
private void DoExport () {
if (GUILayout.Button("Export to PNG")) {
exportFilePath = EditorUtility.SaveFilePanel(
"Export NumberFlow diagram to PNG",
new FileInfo(AssetDatabase.GetAssetPath(diagram)).DirectoryName,
diagram.name,
"png");
if (exportFilePath.Length > 0) {
exporting = true;
exportFrame = -1;
exportRowIndex = 0;
exportOutputIndex = 0;
if (diagram.isCubemap) {
exportDirection = CubemapFace.PositiveX;
exportPixels = new Color[diagram.exportWidth * diagram.exportWidth];
exportCubemapTexture = new Texture2D(diagram.exportWidth * 6, diagram.exportWidth, TextureFormat.ARGB32, false);
}
else {
exportPixels = new Color[diagram.exportWidth * diagram.exportHeight];
}
}
}
if (exporting) {
EditorUtility.DisplayProgressBar(
"Exporting to PNG",
"Output " + diagram.outputs[exportOutputIndex].name,
diagram.isCubemap ? ((float)exportDirection / 6f) : (exportRowIndex / (float)diagram.exportHeight)
);
if (Event.current.type == EventType.Repaint && exportRowIndex == 0 && diagram.exportAnimation) {
exportFrame += 1;
Value animatedValue = diagram.GetInputValue(diagram.exportAnimationInput);
if (animatedValue != null) {
animatedValue.Float = Mathf.Lerp(
diagram.exportAnimateFrom,
diagram.exportAnimateTo,
exportFrame / (float)(diagram.exportAnimationLoop ? diagram.exportAnimationFrames : (diagram.exportAnimationFrames - 1))
);
}
}
if (Event.current.type == EventType.Repaint) {
if (diagram.isCubemap) {
ExportCubemaps();
}
else {
ExportTextures();
}
}
Repaint();
}
}
void ExportTextures () {
exportRowIndex = diagram.FillRows(
exportPixels,
exportOutputIndex,
diagram.exportWidth,
diagram.exportHeight,
exportRowIndex,
diagram.exportHeight / 8 + 1);
if (exportRowIndex >= diagram.exportHeight) {
if (diagram.outputs[exportOutputIndex].type == DiagramTextureType.NormalMap) {
diagram.outputs[exportOutputIndex].GenerateNormalMap(diagram.exportWidth, diagram.exportHeight, exportPixels, DiagramNormalFormat.RGB);
}
Texture2D texture = new Texture2D(
diagram.exportWidth,
diagram.exportHeight,
diagram.outputs[exportOutputIndex].type == DiagramTextureType.RGB || diagram.outputs[exportOutputIndex].type == DiagramTextureType.NormalMap ? TextureFormat.RGB24 : TextureFormat.ARGB32,
false);
texture.SetPixels(exportPixels);
if (diagram.exportAnimation) {
exportRowIndex = exportFrame >= diagram.exportAnimationFrames - 1 ? -1 : 0;
File.WriteAllBytes(exportFilePath.Insert(exportFilePath.Length - 4, diagram.outputs[exportOutputIndex].name + "_" + exportFrame), texture.EncodeToPNG());
}
else {
exportRowIndex = -1;
File.WriteAllBytes(exportFilePath.Insert(exportFilePath.Length - 4, diagram.outputs[exportOutputIndex].name), texture.EncodeToPNG());
}
if (exportRowIndex == -1) {
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
if (++exportOutputIndex < diagram.outputs.Length) {
exportRowIndex = 0;
exportFrame = -1;
}
}
DestroyImmediate(texture);
if (exportRowIndex == -1) {
exporting = false;
}
}
}
void ExportCubemaps () {
ExportCubemapFace();
exportRowIndex = -1;
if (exportDirection == CubemapFace.NegativeZ) {
if (diagram.exportAnimation) {
File.WriteAllBytes(
exportFilePath.Insert(exportFilePath.Length - 4, diagram.outputs[exportOutputIndex].name + "_" + exportFrame),
exportCubemapTexture.EncodeToPNG()
);
exportRowIndex = 0;
if (exportFrame >= diagram.exportAnimationFrames - 1) {
exportOutputIndex += 1;
exportFrame = -1;
}
exporting = exportOutputIndex < diagram.outputs.Length;
}
else {
File.WriteAllBytes(
exportFilePath.Insert(exportFilePath.Length - 4, diagram.outputs[exportOutputIndex].name),
exportCubemapTexture.EncodeToPNG()
);
exportOutputIndex += 1;
exporting = exportOutputIndex < diagram.outputs.Length;
}
exportDirection = CubemapFace.PositiveX;
if (!exporting) {
DestroyImmediate(exportCubemapTexture);
EditorUtility.ClearProgressBar();
AssetDatabase.Refresh();
exportRowIndex = -1;
}
}
else {
exportDirection += 1;
}
}
void ExportCubemapFace () {
int size = diagram.exportWidth;
diagram.cubemapDirection = exportDirection;
diagram.Fill(exportPixels, exportOutputIndex, size, size);
int offset = (int)exportDirection * size;
for (int y = 0; y < size; y++) {
// Need to reverse rows for export.
int row = size * (size - 1 - y);
for (int x = 0; x < size; x++) {
exportCubemapTexture.SetPixel(x + offset, y, exportPixels[row + x]);
}
}
}
[MenuItem("Assets/Create/NumberFlow Diagram")]
public static void CreateNumberFlowDiagram () {
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
if (path.Length == 0) {
// No asset selected, place in asset root.
path = "Assets/New NumberFlow Diagram.asset";
}
else if (Directory.Exists(path)) {
// Place in currently selected directory.
path += "/New NumberFlow Diagram.asset";
}
else {
// Place in current selection's containing directory.
path = Path.GetDirectoryName(path) + "/New NumberFlow Diagram.asset";
}
Diagram newDiagram = ScriptableObject.CreateInstance<Diagram>();
AssetDatabase.CreateAsset(newDiagram, AssetDatabase.GenerateUniqueAssetPath(path));
EditorUtility.FocusProjectWindow();
Selection.activeObject = newDiagram;
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek and Martin Maly.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using PHP.Core;
using System.Diagnostics;
namespace PHP.Library.Data
{
/// <summary>
/// Represents a result of a SQL command.
/// </summary>
public sealed class PhpSqlDbResult : PhpDbResult
{
/// <summary>
/// Limit on size of a batch. Non-positive values means no limit.
/// </summary>
public int BatchSize { get { return batchSize; } set { batchSize = value; } }
private int batchSize = 0;
/// <summary>
/// Creates an instance of a result resource.
/// </summary>
/// <param name="connection">Database connection.</param>
/// <param name="reader">Data reader from which to load results.</param>
/// <param name="convertTypes">Whether to convert resulting values to PHP types.</param>
/// <exception cref="ArgumentNullException">Argument is a <B>null</B> reference.</exception>
public PhpSqlDbResult(PhpDbConnection/*!*/ connection, IDataReader/*!*/ reader, bool convertTypes)
: base(connection, reader, "mssql result", convertTypes)
{
// no code in here
}
internal static PhpSqlDbResult ValidResult(PhpResource handle)
{
PhpSqlDbResult result = handle as PhpSqlDbResult;
if (result != null && result.IsValid) return result;
PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_result_resource"));
return null;
}
/// <summary>
/// Gets an array of column names.
/// </summary>
/// <returns>
/// Array of column names. If a column doesn't have a name (it is calculated),
/// it is assigned "computed{number}" name.
/// </returns>
protected override string[] GetNames()
{
string[] names = base.GetNames();
int j = 0;
for (int i = 0; i < names.Length; i++)
{
if (names[i] == "")
{
names[i] = (j > 0) ? "computed" + j : "computed";
j++;
}
}
return names;
}
/// <summary>
/// Gets row values.
/// </summary>
/// <param name="dataTypes">Data type names.</param>
/// <param name="convertTypes">Whether to convert value to PHP types.</param>
/// <returns>Row data.</returns>
protected override object[] GetValues(string[] dataTypes, bool convertTypes)
{
SqlDataReader sql_reader = (SqlDataReader)this.Reader;
object[] oa = new object[sql_reader.FieldCount];
if (convertTypes)
{
for (int i = 0; i < sql_reader.FieldCount; i++)
oa[i] = ConvertDbValue(sql_reader.GetSqlValue(i));
}
else
{
for (int i = 0; i < sql_reader.FieldCount; i++)
oa[i] = sql_reader.GetSqlValue(i);
}
return oa;
}
/// <summary>
/// Converts a value from database to PHP value.
/// </summary>
/// <param name="dbValue">Database value.</param>
/// <returns>PHP value.</returns>
public static object ConvertDbValue(object dbValue)
{
if (dbValue is SqlInt32)
{
if (dbValue.Equals(SqlInt32.Null)) return null;
else return ((SqlInt32)dbValue).Value;
}
if (dbValue is SqlInt16)
{
if (dbValue.Equals(SqlInt16.Null)) return null;
else return System.Convert.ToInt32(((SqlInt16)dbValue).Value);
}
if (dbValue is SqlBoolean)
{
if (dbValue.Equals(SqlBoolean.Null)) return null;
else return ((SqlBoolean)dbValue).Value ? 1 : 0;
}
if (dbValue is SqlString)
{
if (dbValue.Equals(SqlString.Null)) return null;
else return ((SqlString)dbValue).Value;
}
// TODO: check the format of conversion. Is it culture dependent?
if (dbValue is SqlDateTime)
{
if (dbValue.Equals(SqlDateTime.Null)) return null;
else return ((SqlDateTime)dbValue).Value.ToString("yyyy-MM-dd HH:mm:ss");
}
if (dbValue is SqlDouble)
{
if (dbValue.Equals(SqlDouble.Null)) return null;
else return ((SqlDouble)dbValue).Value;
}
if (dbValue is SqlInt64)
{
if (dbValue.Equals(SqlInt64.Null)) return null;
else return ((SqlInt64)dbValue).Value.ToString();
}
if (dbValue is SqlBinary)
{
if (dbValue.Equals(SqlBinary.Null)) return null;
else return new PHP.Core.PhpBytes(((SqlBinary)dbValue).Value);
}
if (dbValue is SqlDecimal)
{
if (dbValue.Equals(SqlDecimal.Null)) return null;
else return ((SqlDecimal)dbValue).Value.ToString();
}
// TODO: beware of overflow
if (dbValue is SqlMoney)
{
if (dbValue.Equals(SqlMoney.Null)) return null;
else return System.Convert.ToDouble(((SqlMoney)dbValue).Value);
}
if (dbValue is SqlSingle)
{
if (dbValue.Equals(SqlSingle.Null)) return null;
else return System.Convert.ToDouble(((SqlSingle)dbValue).Value);
}
if (dbValue is SqlByte)
{
if (dbValue.Equals(SqlByte.Null)) return null;
else return System.Convert.ToInt32(((SqlByte)dbValue).Value);
}
if (dbValue is SqlGuid)
{
if (dbValue.Equals(SqlGuid.Null)) return null;
else return new PhpBytes(((SqlGuid)dbValue).ToByteArray());
}
Debug.Fail(null);
return dbValue.ToString();
}
/// <summary>
/// Maps database type name to the one displayed by PHP.
/// </summary>
/// <param name="typeName">Database name.</param>
/// <returns>PHP name.</returns>
protected override string MapFieldTypeName(string typeName)
{
switch (typeName)
{
case "bit": return "bit";
case "int":
case "smallint":
case "tinyint": return "int";
case "bigint":
case "numeric": return "numeric";
case "money":
case "smallmoney": return "money";
case "decimal":
case "float":
case "real": return "real";
case "datetime":
case "smalldatetime": return "datetime";
case "char":
case "varchar":
case "sql_variant": return "char";
case "text": return "text";
case "timestamp":
case "uniqueidentifier":
case "binary":
case "varbinary": return "blob";
case "image": return "image";
// Unicode types (Phalanger specific):
case "nvarchar":
case "nchar": return "nchar";
case "ntext": return "ntext";
default: return "unknown";
}
}
/// <summary>
/// Determines whether a type of a specified PHP name is a numeric type.
/// </summary>
/// <param name="phpName">PHP type name.</param>
/// <returns>Whether the type is numeric ("int", "numeric", or "real").</returns>
public bool IsNumericType(string phpName)
{
switch (phpName)
{
case "int":
case "numeric":
case "real":
return true;
default:
return false;
}
}
}
}
| |
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;
namespace Sprint3Test
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
KeyboardState oldKb = Keyboard.GetState();
Texture2D car1, car2, raceTrack;
Rectangle car1Rct, car2Rct, rtRct;
SpriteFont titleFont, menuFont;
SoundEffect blowOut;
bool startGame = false;
//bool car1Won = false, car2Won = false;
int timer = 0, seconds = 0, newSec = 0;
int car1PO = 0, car2PO = 0;
int car1X = 0, car2X = 0;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
graphics.PreferredBackBufferHeight = 800;
graphics.PreferredBackBufferWidth = 1200;
}
/// <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()
{
this.IsMouseVisible = true;
// TODO: Add your initialization logic here
car1Rct = new Rectangle(100, 500, 115, 100);
car2Rct = new Rectangle(800, 500, 115, 100);
rtRct = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
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);
car1 = this.Content.Load<Texture2D>("Race Car #1");
car2 = this.Content.Load<Texture2D>("Race Car #2");
raceTrack = this.Content.Load<Texture2D>("Race Track");
titleFont = this.Content.Load<SpriteFont>("TitleFont");
menuFont = this.Content.Load<SpriteFont>("MenuFont");
blowOut = this.Content.Load<SoundEffect>("BlownEngineSound");
// TODO: use this.Content to load your game content here
}
/// <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)
{
KeyboardState kb = Keyboard.GetState();
// Allows the game to exit
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
// TODO: Add your update logic here
if (kb.IsKeyDown(Keys.Space))
{
startGame = true;
}
if (startGame)
{
timer++;
seconds = 5 - (timer / 60);
if (seconds < 0)
{
newSec = (timer / 60) - 5;
if (kb.IsKeyDown(Keys.Up) &&
!oldKb.IsKeyDown(Keys.Up))
{
car2PO++;
}
if (kb.IsKeyDown(Keys.W) &&
!oldKb.IsKeyDown(Keys.W))
{
car1PO++;
}
if (kb.IsKeyDown(Keys.Down) &&
!oldKb.IsKeyDown(Keys.Down))
{
car2PO--;
}
if (kb.IsKeyDown(Keys.S) &&
!oldKb.IsKeyDown(Keys.S))
{
car1PO--;
}
if (car1PO >= 11)
car1PO = 10;
else if (car1PO <= -1)
car1PO = 0;
if (car2PO >= 11)
car2PO = 10;
else if (car2PO <= -1)
car2PO = 0;
Random rnd = new Random();
int chance = rnd.Next(101);
switch (car1PO)
{
case 5:
if (chance <= 5)
{
car1PO = 0;
blowOut.Play();
}
break;
case 6:
if (chance <= 10)
{
car1PO = 0;
blowOut.Play();
}
break;
case 7:
if (chance <= 15)
{
car1PO = 0;
blowOut.Play();
}
break;
case 8:
if (chance <= 20)
{
car1PO = 0;
blowOut.Play();
}
break;
case 9:
if (chance <= 25)
{
car1PO = 0;
blowOut.Play();
}
break;
case 10:
if (chance <= 30)
{
car1PO = 0;
blowOut.Play();
}
break;
default:
break;
}
switch (car2PO)
{
case 5:
if (chance <= 5)
{
car2PO = 0;
blowOut.Play();
}
break;
case 6:
if (chance <= 10)
{
car2PO = 0;
blowOut.Play();
}
break;
case 7:
if (chance <= 15)
{
car2PO = 0;
blowOut.Play();
}
break;
case 8:
if (chance <= 20)
{
car2PO = 0;
blowOut.Play();
}
break;
case 9:
if (chance <= 25)
{
car2PO = 0;
blowOut.Play();
}
break;
case 10:
if (chance <= 30)
{
car2PO = 0;
blowOut.Play();
}
break;
default:
break;
}
car1X += rnd.Next(car1PO + 1);
car2X += rnd.Next(car2PO + 1);
//if (car1X >= 1200)
// car1Won = true;
//else if (car2X >= 1200)
// car2Won = true;
}
}
oldKb = kb;
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)
{
spriteBatch.Begin();
// TODO: Add your drawing code here
if (startGame)
{
GraphicsDevice.Clear(Color.Black);
if (seconds >= 0)
spriteBatch.DrawString(titleFont, seconds + "", new Vector2(260, 300), Color.White);
else
//if (!car1Won && !car2Won)
{
spriteBatch.Draw(raceTrack, rtRct, Color.White);
car1Rct = new Rectangle(car1X, 275, 115, 100);
spriteBatch.Draw(car1, car1Rct, Color.White);
car2Rct = new Rectangle(car2X, 500, 115, 100);
spriteBatch.Draw(car2, car2Rct, Color.White);
spriteBatch.DrawString(titleFont, newSec + "sec", new Vector2(1100, 100), Color.White);
spriteBatch.DrawString(menuFont, "Car1: " + car1PO, new Vector2(0, 0), Color.White);
spriteBatch.DrawString(menuFont, "Car2: " + car2PO, new Vector2(1000, 0), Color.White);
}
//else
//{
// if (car1Won)
// spriteBatch.DrawString(menuFont, "Car1: " + car1PO, new Vector2(0, 0), Color.White);
// else
// spriteBatch.DrawString(menuFont, "Car2: " + car2PO, new Vector2(1000, 0), Color.White);
//}
} else
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.DrawString(titleFont, "Welcome to the CTE Center Raceway", new Vector2(260, 300), Color.White);
spriteBatch.DrawString(menuFont, "Hit the SPACE to begin", new Vector2(450, 340), Color.White);
spriteBatch.Draw(car1, car1Rct, Color.White);
spriteBatch.DrawString(menuFont, "W - increase speed\nS - decrease speed", new Vector2(70, 600), Color.White);
spriteBatch.Draw(car2, car2Rct, Color.White);
spriteBatch.DrawString(menuFont, "UP ARROW - increase speed\nDOWN ARROW - decrease speed", new Vector2(770, 600), Color.White);
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using QuantConnect.Securities.Future;
using QuantConnect.Util;
namespace QuantConnect.Data.Market
{
/// <summary>
/// Represents an entire chain of futures contracts for a single underlying
/// This type is <see cref="IEnumerable{FuturesContract}"/>
/// </summary>
public class FuturesChain : BaseData, IEnumerable<FuturesContract>
{
private readonly Dictionary<Type, Dictionary<Symbol, List<BaseData>>> _auxiliaryData = new Dictionary<Type, Dictionary<Symbol, List<BaseData>>>();
/// <summary>
/// Gets the most recent trade information for the underlying. This may
/// be a <see cref="Tick"/> or a <see cref="TradeBar"/>
/// </summary>
public BaseData Underlying
{
get; internal set;
}
/// <summary>
/// Gets all ticks for every futures contract in this chain, keyed by symbol
/// </summary>
public Ticks Ticks
{
get; private set;
}
/// <summary>
/// Gets all trade bars for every futures contract in this chain, keyed by symbol
/// </summary>
public TradeBars TradeBars
{
get; private set;
}
/// <summary>
/// Gets all quote bars for every futures contract in this chain, keyed by symbol
/// </summary>
public QuoteBars QuoteBars
{
get; private set;
}
/// <summary>
/// Gets all contracts in the chain, keyed by symbol
/// </summary>
public FuturesContracts Contracts
{
get; private set;
}
/// <summary>
/// Gets the set of symbols that passed the <see cref="Future.ContractFilter"/>
/// </summary>
public HashSet<Symbol> FilteredContracts
{
get; private set;
}
/// <summary>
/// Initializes a new default instance of the <see cref="FuturesChain"/> class
/// </summary>
private FuturesChain()
{
DataType = MarketDataType.FuturesChain;
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
FilteredContracts = new HashSet<Symbol>();
}
/// <summary>
/// Initializes a new instance of the <see cref="FuturesChain"/> class
/// </summary>
/// <param name="canonicalFutureSymbol">The symbol for this chain.</param>
/// <param name="time">The time of this chain</param>
/// <param name="trades">All trade data for the entire futures chain</param>
/// <param name="quotes">All quote data for the entire futures chain</param>
/// <param name="contracts">All contracts for this futures chain</param>
/// <param name="filteredContracts">The filtered list of contracts for this futures chain</param>
public FuturesChain(Symbol canonicalFutureSymbol, DateTime time, IEnumerable<BaseData> trades, IEnumerable<BaseData> quotes, IEnumerable<FuturesContract> contracts, IEnumerable<Symbol> filteredContracts)
{
Time = time;
Symbol = canonicalFutureSymbol;
DataType = MarketDataType.FuturesChain;
FilteredContracts = filteredContracts.ToHashSet();
Ticks = new Ticks(time);
TradeBars = new TradeBars(time);
QuoteBars = new QuoteBars(time);
Contracts = new FuturesContracts(time);
foreach (var trade in trades)
{
var tick = trade as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = trade as TradeBar;
if (bar != null)
{
TradeBars[trade.Symbol] = bar;
}
}
foreach (var quote in quotes)
{
var tick = quote as Tick;
if (tick != null)
{
List<Tick> ticks;
if (!Ticks.TryGetValue(tick.Symbol, out ticks))
{
ticks = new List<Tick>();
Ticks[tick.Symbol] = ticks;
}
ticks.Add(tick);
continue;
}
var bar = quote as QuoteBar;
if (bar != null)
{
QuoteBars[quote.Symbol] = bar;
}
}
foreach (var contract in contracts)
{
Contracts[contract.Symbol] = contract;
}
}
/// <summary>
/// Gets the auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The last auxiliary data with the specified type and symbol</returns>
public T GetAux<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return default(T);
}
return list.OfType<T>().LastOrDefault();
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public DataDictionary<T> GetAux<T>()
{
Dictionary<Symbol, List<BaseData>> d;
if (!_auxiliaryData.TryGetValue(typeof(T), out d))
{
return new DataDictionary<T>();
}
var dictionary = new DataDictionary<T>();
foreach (var kvp in d)
{
var item = kvp.Value.OfType<T>().LastOrDefault();
if (item != null)
{
dictionary.Add(kvp.Key, item);
}
}
return dictionary;
}
/// <summary>
/// Gets all auxiliary data of the specified type as a dictionary keyed by symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <returns>A dictionary containing all auxiliary data of the specified type</returns>
public Dictionary<Symbol, List<BaseData>> GetAuxList<T>()
{
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary))
{
return new Dictionary<Symbol, List<BaseData>>();
}
return dictionary;
}
/// <summary>
/// Gets a list of auxiliary data with the specified type and symbol
/// </summary>
/// <typeparam name="T">The type of auxiliary data</typeparam>
/// <param name="symbol">The symbol of the auxiliary data</param>
/// <returns>The list of auxiliary data with the specified type and symbol</returns>
public List<T> GetAuxList<T>(Symbol symbol)
{
List<BaseData> list;
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(typeof(T), out dictionary) || !dictionary.TryGetValue(symbol, out list))
{
return new List<T>();
}
return list.OfType<T>().ToList();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// An enumerator that can be used to iterate through the collection.
/// </returns>
public IEnumerator<FuturesContract> GetEnumerator()
{
return Contracts.Values.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Return a new instance clone of this object, used in fill forward
/// </summary>
/// <returns>A clone of the current object</returns>
public override BaseData Clone()
{
return new FuturesChain
{
Ticks = Ticks,
Contracts = Contracts,
QuoteBars = QuoteBars,
TradeBars = TradeBars,
FilteredContracts = FilteredContracts,
Symbol = Symbol,
Time = Time,
DataType = DataType,
Value = Value
};
}
/// <summary>
/// Adds the specified auxiliary data to this futures chain
/// </summary>
/// <param name="baseData">The auxiliary data to be added</param>
internal void AddAuxData(BaseData baseData)
{
var type = baseData.GetType();
Dictionary<Symbol, List<BaseData>> dictionary;
if (!_auxiliaryData.TryGetValue(type, out dictionary))
{
dictionary = new Dictionary<Symbol, List<BaseData>>();
_auxiliaryData[type] = dictionary;
}
List<BaseData> list;
if (!dictionary.TryGetValue(baseData.Symbol, out list))
{
list = new List<BaseData>();
dictionary[baseData.Symbol] = list;
}
list.Add(baseData);
}
}
}
| |
// 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.CompilerServices;
using System.Runtime.InteropServices;
using Internal.Runtime.CompilerServices;
namespace System
{
// The BitConverter class contains methods for
// converting an array of bytes to one of the base data
// types, as well as for converting a base data type to an
// array of bytes.
public static class BitConverter
{
// This field indicates the "endianess" of the architecture.
// The value is set to true if the architecture is
// little endian; false if it is big endian.
#if BIGENDIAN
[Intrinsic]
public static readonly bool IsLittleEndian /* = false */;
#else
[Intrinsic]
public static readonly bool IsLittleEndian = true;
#endif
// Converts a Boolean into an array of bytes with length one.
public static byte[] GetBytes(bool value)
{
byte[] r = new byte[1];
r[0] = (value ? (byte)1 : (byte)0);
return r;
}
// Converts a Boolean into a Span of bytes with length one.
public static bool TryWriteBytes(Span<byte> destination, bool value)
{
if (destination.Length < sizeof(byte))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value ? (byte)1 : (byte)0);
return true;
}
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
byte[] bytes = new byte[sizeof(char)];
Unsafe.As<byte, char>(ref bytes[0]) = value;
return bytes;
}
// Converts a char into a Span
public static bool TryWriteBytes(Span<byte> destination, char value)
{
if (destination.Length < sizeof(char))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a short into an array of bytes with length
// two.
public static byte[] GetBytes(short value)
{
byte[] bytes = new byte[sizeof(short)];
Unsafe.As<byte, short>(ref bytes[0]) = value;
return bytes;
}
// Converts a short into a Span
public static bool TryWriteBytes(Span<byte> destination, short value)
{
if (destination.Length < sizeof(short))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an int into an array of bytes with length
// four.
public static byte[] GetBytes(int value)
{
byte[] bytes = new byte[sizeof(int)];
Unsafe.As<byte, int>(ref bytes[0]) = value;
return bytes;
}
// Converts an int into a Span
public static bool TryWriteBytes(Span<byte> destination, int value)
{
if (destination.Length < sizeof(int))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a long into an array of bytes with length
// eight.
public static byte[] GetBytes(long value)
{
byte[] bytes = new byte[sizeof(long)];
Unsafe.As<byte, long>(ref bytes[0]) = value;
return bytes;
}
// Converts a long into a Span
public static bool TryWriteBytes(Span<byte> destination, long value)
{
if (destination.Length < sizeof(long))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
public static byte[] GetBytes(ushort value)
{
byte[] bytes = new byte[sizeof(ushort)];
Unsafe.As<byte, ushort>(ref bytes[0]) = value;
return bytes;
}
// Converts a ushort into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, ushort value)
{
if (destination.Length < sizeof(ushort))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
public static byte[] GetBytes(uint value)
{
byte[] bytes = new byte[sizeof(uint)];
Unsafe.As<byte, uint>(ref bytes[0]) = value;
return bytes;
}
// Converts a uint into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, uint value)
{
if (destination.Length < sizeof(uint))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
public static byte[] GetBytes(ulong value)
{
byte[] bytes = new byte[sizeof(ulong)];
Unsafe.As<byte, ulong>(ref bytes[0]) = value;
return bytes;
}
// Converts a ulong into a Span
[CLSCompliant(false)]
public static bool TryWriteBytes(Span<byte> destination, ulong value)
{
if (destination.Length < sizeof(ulong))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a float into an array of bytes with length
// four.
public static byte[] GetBytes(float value)
{
byte[] bytes = new byte[sizeof(float)];
Unsafe.As<byte, float>(ref bytes[0]) = value;
return bytes;
}
// Converts a float into a Span
public static bool TryWriteBytes(Span<byte> destination, float value)
{
if (destination.Length < sizeof(float))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts a double into an array of bytes with length
// eight.
public static byte[] GetBytes(double value)
{
byte[] bytes = new byte[sizeof(double)];
Unsafe.As<byte, double>(ref bytes[0]) = value;
return bytes;
}
// Converts a double into a Span
public static bool TryWriteBytes(Span<byte> destination, double value)
{
if (destination.Length < sizeof(double))
return false;
Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value);
return true;
}
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex) => unchecked((char)ToInt16(value, startIndex));
// Converts a Span into a char
public static char ToChar(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(char))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<char>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a short.
public static short ToInt16(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(short))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<short>(ref value[startIndex]);
}
// Converts a Span into a short
public static short ToInt16(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(short))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<short>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an int.
public static int ToInt32(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(int))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<int>(ref value[startIndex]);
}
// Converts a Span into an int
public static int ToInt32(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(int))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<int>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a long.
public static long ToInt64(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (unchecked((uint)startIndex) >= unchecked((uint)value.Length))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - sizeof(long))
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
return Unsafe.ReadUnaligned<long>(ref value[startIndex]);
}
// Converts a Span into a long
public static long ToInt64(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(long))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<long>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ToInt16(value, startIndex));
// Converts a Span into a ushort
[CLSCompliant(false)]
public static ushort ToUInt16(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(ushort))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<ushort>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ToInt32(value, startIndex));
// Convert a Span into a uint
[CLSCompliant(false)]
public static uint ToUInt32(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(uint))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<uint>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ToInt64(value, startIndex));
// Converts a Span into an unsigned long
[CLSCompliant(false)]
public static ulong ToUInt64(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(ulong))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<ulong>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a float.
public static float ToSingle(byte[] value, int startIndex) => Int32BitsToSingle(ToInt32(value, startIndex));
// Converts a Span into a float
public static float ToSingle(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(float))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<float>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a double.
public static double ToDouble(byte[] value, int startIndex) => Int64BitsToDouble(ToInt64(value, startIndex));
// Converts a Span into a double
public static double ToDouble(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(double))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<double>(ref MemoryMarshal.GetReference(value));
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex, int length)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0 || startIndex >= value.Length && startIndex > 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (length < 0)
throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_GenericPositive);
if (startIndex > value.Length - length)
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value);
if (length == 0)
{
return string.Empty;
}
if (length > (int.MaxValue / 3))
{
// (int.MaxValue / 3) == 715,827,882 Bytes == 699 MB
throw new ArgumentOutOfRangeException(nameof(length), SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, (int.MaxValue / 3)));
}
return string.Create(length * 3 - 1, (value, startIndex, length), (dst, state) =>
{
const string HexValues = "0123456789ABCDEF";
var src = new ReadOnlySpan<byte>(state.value, state.startIndex, state.length);
int i = 0;
int j = 0;
byte b = src[i++];
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
while (i < src.Length)
{
b = src[i++];
dst[j++] = '-';
dst[j++] = HexValues[b >> 4];
dst[j++] = HexValues[b & 0xF];
}
});
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
return ToString(value, 0, value.Length);
}
// Converts an array of bytes into a String.
public static string ToString(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
return ToString(value, startIndex, value.Length - startIndex);
}
/*==================================ToBoolean===================================
**Action: Convert an array of bytes to a boolean value. We treat this array
** as if the first 4 bytes were an Int4 an operate on this value.
**Returns: True if the Int4 value of the first 4 bytes is non-zero.
**Arguments: value -- The byte array
** startIndex -- The position within the array.
**Exceptions: See ToInt4.
==============================================================================*/
// Converts an array of bytes into a boolean.
public static bool ToBoolean(byte[] value, int startIndex)
{
if (value == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
if (startIndex < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
if (startIndex > value.Length - 1)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); // differs from other overloads, which throw base ArgumentException
return value[startIndex] != 0;
}
public static bool ToBoolean(ReadOnlySpan<byte> value)
{
if (value.Length < sizeof(byte))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
return Unsafe.ReadUnaligned<byte>(ref MemoryMarshal.GetReference(value)) != 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe long DoubleToInt64Bits(double value)
{
return *((long*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe double Int64BitsToDouble(long value)
{
return *((double*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe int SingleToInt32Bits(float value)
{
return *((int*)&value);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe float Int32BitsToSingle(int value)
{
return *((float*)&value);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
/// <summary>
/// System.Math.Atan2(System.Double,System.Double)
/// </summary>
public class MathAtan2
{
public static int Main(string[] args)
{
MathAtan2 arctan2 = new MathAtan2();
TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Atan2(System.Double,System.Double)...");
if (arctan2.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify the angle of arctan(x,y) when the point in quadrant one...");
try
{
double x = TestLibrary.Generator.GetDouble(-55);
while (x <= 0)
{
x = TestLibrary.Generator.GetDouble(-55);
}
double y = TestLibrary.Generator.GetDouble(-55);
while (y <= 0)
{
y = TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y,x);
if (angle > Math.PI / 2 || angle < 0)
{
TestLibrary.TestFramework.LogError("001", "The angle should be between 0 and Math.PI/2, actual: " +
angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Verify the angle of arctan(x,y) when the point in quadrant four...");
try
{
double x = TestLibrary.Generator.GetDouble(-55);
while (x <= 0)
{
x = TestLibrary.Generator.GetDouble(-55);
}
double y = TestLibrary.Generator.GetDouble(-55);
while (y >= 0)
{
y = -TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y, x);
if (angle > 0 || angle < -Math.PI / 2)
{
TestLibrary.TestFramework.LogError("003", "The angle should be between 0 and -Math.PI/2, actual: " +
angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Verify the angle of arctan(x,y) when the point in forward direction of X axis...");
try
{
double x = TestLibrary.Generator.GetDouble(-55);
while (x <= 0)
{
x = TestLibrary.Generator.GetDouble(-55);
}
double y = 0;
double angle = Math.Atan2(y, x);
if (!MathTestLib.DoubleIsWithinEpsilon(angle ,0.0))
{
TestLibrary.TestFramework.LogError("005", "The angle should be zero,actual: "+angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Verify the angle of arctan(x,y) when the point in forward direction of Y axis...");
try
{
double x = 0;
double y = TestLibrary.Generator.GetDouble(-55);
while (y <= 0)
{
y = TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y, x);
if (!MathTestLib.DoubleIsWithinEpsilon(angle ,Math.PI / 2))
{
TestLibrary.TestFramework.LogError("007", "The angle should be pi/2, actual:"+angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Verify the angle of arctan(x,y) when the point in negative direction of Y axis...");
try
{
double x = 0;
double y = TestLibrary.Generator.GetDouble(-55);
while (y >= 0)
{
y = -TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y, x);
if (!MathTestLib.DoubleIsWithinEpsilon(angle ,-Math.PI / 2))
{
TestLibrary.TestFramework.LogError("009", "The angle should be -pi/2, actual: "+angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest6: Verify the angle of arctan(x,y) when the point in quadrant two...");
try
{
double x = TestLibrary.Generator.GetDouble(-55);
while (x >= 0)
{
x = -TestLibrary.Generator.GetDouble(-55);
}
double y = TestLibrary.Generator.GetDouble(-55);
while (y <= 0)
{
y = TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y, x);
if (angle < Math.PI / 2 || angle > Math.PI)
{
TestLibrary.TestFramework.LogError("011", "The angle should be between 0 and Math.PI/2, actual: " + angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest7: Verify the angle of arctan(x,y) when the point in quadrant three...");
try
{
double x = TestLibrary.Generator.GetDouble(-55);
while (x >= 0)
{
x = -TestLibrary.Generator.GetDouble(-55);
}
double y = TestLibrary.Generator.GetDouble(-55);
while (y >= 0)
{
y = -TestLibrary.Generator.GetDouble(-55);
}
double angle = Math.Atan2(y, x);
if (angle > -Math.PI / 2 || angle < -Math.PI)
{
TestLibrary.TestFramework.LogError("013", "The angle should be between 0 and Math.PI/2, actual: " +
angle.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception occurs: " + e);
retVal = false;
}
return retVal;
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using log4net;
#if CSharpSqlite
using Community.CsharpSqlite.Sqlite;
#else
using Mono.Data.Sqlite;
#endif
using OpenMetaverse;
using OpenSim.Framework;
namespace OpenSim.Data.SQLite
{
/// <summary>
/// An Inventory Interface to the SQLite database
/// </summary>
public class SQLiteInventoryStore : SQLiteUtil, IInventoryDataPlugin
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private const string invItemsSelect = "select * from inventoryitems";
private const string invFoldersSelect = "select * from inventoryfolders";
private static SqliteConnection conn;
private static DataSet ds;
private static SqliteDataAdapter invItemsDa;
private static SqliteDataAdapter invFoldersDa;
private static bool m_Initialized = false;
public void Initialise()
{
m_log.Info("[SQLiteInventoryData]: " + Name + " cannot be default-initialized!");
throw new PluginNotInitialisedException(Name);
}
/// <summary>
/// <list type="bullet">
/// <item>Initialises Inventory interface</item>
/// <item>Loads and initialises a new SQLite connection and maintains it.</item>
/// <item>use default URI if connect string string is empty.</item>
/// </list>
/// </summary>
/// <param name="dbconnect">connect string</param>
public void Initialise(string dbconnect)
{
if (!m_Initialized)
{
m_Initialized = true;
if (Util.IsWindows())
Util.LoadArchSpecificWindowsDll("sqlite3.dll");
if (dbconnect == string.Empty)
{
dbconnect = "URI=file:inventoryStore.db,version=3";
}
m_log.Info("[INVENTORY DB]: Sqlite - connecting: " + dbconnect);
conn = new SqliteConnection(dbconnect);
conn.Open();
Assembly assem = GetType().Assembly;
Migration m = new Migration(conn, assem, "InventoryStore");
m.Update();
SqliteCommand itemsSelectCmd = new SqliteCommand(invItemsSelect, conn);
invItemsDa = new SqliteDataAdapter(itemsSelectCmd);
// SqliteCommandBuilder primCb = new SqliteCommandBuilder(primDa);
SqliteCommand foldersSelectCmd = new SqliteCommand(invFoldersSelect, conn);
invFoldersDa = new SqliteDataAdapter(foldersSelectCmd);
ds = new DataSet();
ds.Tables.Add(createInventoryFoldersTable());
invFoldersDa.Fill(ds.Tables["inventoryfolders"]);
setupFoldersCommands(invFoldersDa, conn);
CreateDataSetMapping(invFoldersDa, "inventoryfolders");
m_log.Info("[INVENTORY DB]: Populated Inventory Folders Definitions");
ds.Tables.Add(createInventoryItemsTable());
invItemsDa.Fill(ds.Tables["inventoryitems"]);
setupItemsCommands(invItemsDa, conn);
CreateDataSetMapping(invItemsDa, "inventoryitems");
m_log.Info("[INVENTORY DB]: Populated Inventory Items Definitions");
ds.AcceptChanges();
}
}
/// <summary>
/// Closes the inventory interface
/// </summary>
public void Dispose()
{
if (conn != null)
{
conn.Close();
conn = null;
}
if (invItemsDa != null)
{
invItemsDa.Dispose();
invItemsDa = null;
}
if (invFoldersDa != null)
{
invFoldersDa.Dispose();
invFoldersDa = null;
}
if (ds != null)
{
ds.Dispose();
ds = null;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
public InventoryItemBase buildItem(DataRow row)
{
InventoryItemBase item = new InventoryItemBase();
item.ID = new UUID((string) row["UUID"]);
item.AssetID = new UUID((string) row["assetID"]);
item.AssetType = Convert.ToInt32(row["assetType"]);
item.InvType = Convert.ToInt32(row["invType"]);
item.Folder = new UUID((string) row["parentFolderID"]);
item.Owner = new UUID((string) row["avatarID"]);
item.CreatorIdentification = (string)row["creatorsID"];
item.Name = (string) row["inventoryName"];
item.Description = (string) row["inventoryDescription"];
item.NextPermissions = Convert.ToUInt32(row["inventoryNextPermissions"]);
item.CurrentPermissions = Convert.ToUInt32(row["inventoryCurrentPermissions"]);
item.BasePermissions = Convert.ToUInt32(row["inventoryBasePermissions"]);
item.EveryOnePermissions = Convert.ToUInt32(row["inventoryEveryOnePermissions"]);
item.GroupPermissions = Convert.ToUInt32(row["inventoryGroupPermissions"]);
// new fields
if (!Convert.IsDBNull(row["salePrice"]))
item.SalePrice = Convert.ToInt32(row["salePrice"]);
if (!Convert.IsDBNull(row["saleType"]))
item.SaleType = Convert.ToByte(row["saleType"]);
if (!Convert.IsDBNull(row["creationDate"]))
item.CreationDate = Convert.ToInt32(row["creationDate"]);
if (!Convert.IsDBNull(row["groupID"]))
item.GroupID = new UUID((string)row["groupID"]);
if (!Convert.IsDBNull(row["groupOwned"]))
item.GroupOwned = Convert.ToBoolean(row["groupOwned"]);
if (!Convert.IsDBNull(row["Flags"]))
item.Flags = Convert.ToUInt32(row["Flags"]);
return item;
}
/// <summary>
/// Fill a database row with item data
/// </summary>
/// <param name="row"></param>
/// <param name="item"></param>
private static void fillItemRow(DataRow row, InventoryItemBase item)
{
row["UUID"] = item.ID.ToString();
row["assetID"] = item.AssetID.ToString();
row["assetType"] = item.AssetType;
row["invType"] = item.InvType;
row["parentFolderID"] = item.Folder.ToString();
row["avatarID"] = item.Owner.ToString();
row["creatorsID"] = item.CreatorIdentification.ToString();
row["inventoryName"] = item.Name;
row["inventoryDescription"] = item.Description;
row["inventoryNextPermissions"] = item.NextPermissions;
row["inventoryCurrentPermissions"] = item.CurrentPermissions;
row["inventoryBasePermissions"] = item.BasePermissions;
row["inventoryEveryOnePermissions"] = item.EveryOnePermissions;
row["inventoryGroupPermissions"] = item.GroupPermissions;
// new fields
row["salePrice"] = item.SalePrice;
row["saleType"] = item.SaleType;
row["creationDate"] = item.CreationDate;
row["groupID"] = item.GroupID.ToString();
row["groupOwned"] = item.GroupOwned;
row["flags"] = item.Flags;
}
/// <summary>
/// Add inventory folder
/// </summary>
/// <param name="folder">Folder base</param>
/// <param name="add">true=create folder. false=update existing folder</param>
/// <remarks>nasty</remarks>
private void addFolder(InventoryFolderBase folder, bool add)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
if (! add)
m_log.ErrorFormat("Interface Misuse: Attempting to Update non-existent inventory folder: {0}", folder.ID);
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("Interface Misuse: Attempting to Add inventory folder that already exists: {0}", folder.ID);
fillFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// Move an inventory folder
/// </summary>
/// <param name="folder">folder base</param>
private void moveFolder(InventoryFolderBase folder)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow = inventoryFolderTable.Rows.Find(folder.ID.ToString());
if (inventoryRow == null)
{
inventoryRow = inventoryFolderTable.NewRow();
fillFolderRow(inventoryRow, folder);
inventoryFolderTable.Rows.Add(inventoryRow);
}
else
{
moveFolderRow(inventoryRow, folder);
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// add an item in inventory
/// </summary>
/// <param name="item">the item</param>
/// <param name="add">true=add item ; false=update existing item</param>
private void addItem(InventoryItemBase item, bool add)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(item.ID.ToString());
if (inventoryRow == null)
{
if (!add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Update non-existent inventory item: {0}", item.ID);
inventoryRow = inventoryItemTable.NewRow();
fillItemRow(inventoryRow, item);
inventoryItemTable.Rows.Add(inventoryRow);
}
else
{
if (add)
m_log.ErrorFormat("[INVENTORY DB]: Interface Misuse: Attempting to Add inventory item that already exists: {0}", item.ID);
fillItemRow(inventoryRow, item);
}
invItemsDa.Update(ds, "inventoryitems");
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
inventoryRow = inventoryFolderTable.Rows.Find(item.Folder.ToString());
if (inventoryRow != null) //MySQL doesn't throw an exception here, so sqlite shouldn't either.
inventoryRow["version"] = (int)inventoryRow["version"] + 1;
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/// <summary>
/// TODO : DataSet commit
/// </summary>
public void Shutdown()
{
// TODO: DataSet commit
}
/// <summary>
/// The name of this DB provider
/// </summary>
/// <returns>Name of DB provider</returns>
public string Name
{
get { return "SQLite Inventory Data Interface"; }
}
/// <summary>
/// Returns the version of this DB provider
/// </summary>
/// <returns>A string containing the DB provider version</returns>
public string Version
{
get
{
Module module = GetType().Module;
// string dllName = module.Assembly.ManifestModule.Name;
Version dllVersion = module.Assembly.GetName().Version;
return
string.Format("{0}.{1}.{2}.{3}", dllVersion.Major, dllVersion.Minor, dllVersion.Build,
dllVersion.Revision);
}
}
/// <summary>
/// Returns a list of inventory items contained within the specified folder
/// </summary>
/// <param name="folderID">The UUID of the target folder</param>
/// <returns>A List of InventoryItemBase items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
lock (ds)
{
List<InventoryItemBase> retval = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp = "parentFolderID = '" + folderID + "'";
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
retval.Add(buildItem(row));
}
return retval;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user)
{
return new List<InventoryFolderBase>();
}
// see InventoryItemBase.getUserRootFolder
public InventoryFolderBase getUserRootFolder(UUID user)
{
lock (ds)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "agentID = '" + user + "' AND parentID = '" + UUID.Zero + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (folders.Count > 0)
{
return folders[0];
}
return null;
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
/// </summary>
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
{
lock (ds)
{
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "parentID = '" + parentID + "'";
DataRow[] rows = inventoryFolderTable.Select(selectExp);
foreach (DataRow row in rows)
{
folders.Add(buildFolder(row));
}
}
}
/// <summary>
/// Returns a list of inventory folders contained in the folder 'parentID'
/// </summary>
/// <param name="parentID">The folder to get subfolders for</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
getInventoryFolders(ref folders, parentID);
return folders;
}
/// <summary>
/// See IInventoryDataPlugin
/// </summary>
/// <param name="parentID"></param>
/// <returns></returns>
public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
{
/* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
* - We will only need to hit the database twice instead of n times.
* - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
* by the same person, each user only has 1 inventory heirarchy
* - The returned list is not ordered, instead of breadth-first ordered
There are basically 2 usage cases for getFolderHeirarchy:
1) Getting the user's entire inventory heirarchy when they log in
2) Finding a subfolder heirarchy to delete when emptying the trash.
This implementation will pull all inventory folders from the database, and then prune away any folder that
is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
database than to make n requests. This pays off only if requested heirarchy is large.
By making this choice, we are making the worst case better at the cost of making the best case worse
- Francis
*/
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
DataRow[] folderRows = null, parentRow;
InventoryFolderBase parentFolder = null;
lock (ds)
{
/* Fetch the parent folder from the database to determine the agent ID.
* Then fetch all inventory folders for that agent from the agent ID.
*/
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
string selectExp = "UUID = '" + parentID + "'";
parentRow = inventoryFolderTable.Select(selectExp); // Assume at most 1 result
if (parentRow.GetLength(0) >= 1) // No result means parent folder does not exist
{
parentFolder = buildFolder(parentRow[0]);
UUID agentID = parentFolder.Owner;
selectExp = "agentID = '" + agentID + "'";
folderRows = inventoryFolderTable.Select(selectExp);
}
if (folderRows != null && folderRows.GetLength(0) >= 1) // No result means parent folder does not exist
{ // or has no children
/* if we're querying the root folder, just return an unordered list of all folders in the user's
* inventory
*/
if (parentFolder.ParentID == UUID.Zero)
{
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ID != parentID) // Return all folders except the parent folder of heirarchy
folders.Add(buildFolder(row));
}
} // If requesting root folder
/* else we are querying a non-root folder. We currently have a list of all of the user's folders,
* we must construct a list of all folders in the heirarchy below parentID.
* Our first step will be to construct a hash table of all folders, indexed by parent ID.
* Once we have constructed the hash table, we will do a breadth-first traversal on the tree using the
* hash table to find child folders.
*/
else
{ // Querying a non-root folder
// Build a hash table of all user's inventory folders, indexed by each folder's parent ID
Dictionary<UUID, List<InventoryFolderBase>> hashtable =
new Dictionary<UUID, List<InventoryFolderBase>>(folderRows.GetLength(0));
foreach (DataRow row in folderRows)
{
InventoryFolderBase curFolder = buildFolder(row);
if (curFolder.ParentID != UUID.Zero) // Discard root of tree - not needed
{
if (hashtable.ContainsKey(curFolder.ParentID))
{
// Current folder already has a sibling - append to sibling list
hashtable[curFolder.ParentID].Add(curFolder);
}
else
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
}
}
} // For all inventory folders
// Note: Could release the ds lock here - we don't access folderRows or the database anymore.
// This is somewhat of a moot point as the callers of this function usually lock db anyways.
if (hashtable.ContainsKey(parentID)) // if requested folder does have children
folders.AddRange(hashtable[parentID]);
// BreadthFirstSearch build inventory tree **Note: folders.Count is *not* static
for (int i = 0; i < folders.Count; i++)
if (hashtable.ContainsKey(folders[i].ID))
folders.AddRange(hashtable[folders[i].ID]);
} // if requesting a subfolder heirarchy
} // if folder parentID exists and has children
} // lock ds
return folders;
}
/// <summary>
/// Returns an inventory item by its UUID
/// </summary>
/// <param name="item">The UUID of the item to be returned</param>
/// <returns>A class containing item information</returns>
public InventoryItemBase getInventoryItem(UUID item)
{
lock (ds)
{
DataRow row = ds.Tables["inventoryitems"].Rows.Find(item.ToString());
if (row != null)
{
return buildItem(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Returns a specified inventory folder by its UUID
/// </summary>
/// <param name="folder">The UUID of the folder to be returned</param>
/// <returns>A class containing folder information</returns>
public InventoryFolderBase getInventoryFolder(UUID folder)
{
// TODO: Deep voodoo here. If you enable this code then
// multi region breaks. No idea why, but I figured it was
// better to leave multi region at this point. It does mean
// that you don't get to see system textures why creating
// clothes and the like. :(
lock (ds)
{
DataRow row = ds.Tables["inventoryfolders"].Rows.Find(folder.ToString());
if (row != null)
{
return buildFolder(row);
}
else
{
return null;
}
}
}
/// <summary>
/// Creates a new inventory item based on item
/// </summary>
/// <param name="item">The item to be created</param>
public void addInventoryItem(InventoryItemBase item)
{
addItem(item, true);
}
/// <summary>
/// Updates an inventory item with item (updates based on ID)
/// </summary>
/// <param name="item">The updated item</param>
public void updateInventoryItem(InventoryItemBase item)
{
addItem(item, false);
}
/// <summary>
/// Delete an inventory item
/// </summary>
/// <param name="item">The item UUID</param>
public void deleteInventoryItem(UUID itemID)
{
lock (ds)
{
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
DataRow inventoryRow = inventoryItemTable.Rows.Find(itemID.ToString());
if (inventoryRow != null)
{
inventoryRow.Delete();
}
invItemsDa.Update(ds, "inventoryitems");
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Delete all items in the specified folder
/// </summary>
/// <param name="folderId">id of the folder, whose item content should be deleted</param>
/// <todo>this is horribly inefficient, but I don't want to ruin the overall structure of this implementation</todo>
private void deleteItemsInFolder(UUID folderId)
{
List<InventoryItemBase> items = getInventoryInFolder(folderId);
foreach (InventoryItemBase i in items)
deleteInventoryItem(i.ID);
}
/// <summary>
/// Adds a new folder specified by folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void addInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, true);
}
/// <summary>
/// Updates a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void updateInventoryFolder(InventoryFolderBase folder)
{
addFolder(folder, false);
}
/// <summary>
/// Moves a folder based on its ID with folder
/// </summary>
/// <param name="folder">The inventory folder</param>
public void moveInventoryFolder(InventoryFolderBase folder)
{
moveFolder(folder);
}
/// <summary>
/// Delete a folder
/// </summary>
/// <remarks>
/// This will clean-up any child folders and child items as well
/// </remarks>
/// <param name="folderID">the folder UUID</param>
public void deleteInventoryFolder(UUID folderID)
{
lock (ds)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
DataTable inventoryFolderTable = ds.Tables["inventoryfolders"];
DataRow inventoryRow;
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
inventoryRow = inventoryFolderTable.Rows.Find(f.ID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(f.ID);
inventoryRow.Delete();
}
}
//Delete the actual row
inventoryRow = inventoryFolderTable.Rows.Find(folderID.ToString());
if (inventoryRow != null)
{
deleteItemsInFolder(folderID);
inventoryRow.Delete();
}
invFoldersDa.Update(ds, "inventoryfolders");
}
}
/***********************************************************************
*
* Data Table definitions
*
**********************************************************************/
protected void CreateDataSetMapping(IDataAdapter da, string tableName)
{
ITableMapping dbMapping = da.TableMappings.Add(tableName, tableName);
foreach (DataColumn col in ds.Tables[tableName].Columns)
{
dbMapping.ColumnMappings.Add(col.ColumnName, col.ColumnName);
}
}
/// <summary>
/// Create the "inventoryitems" table
/// </summary>
private static DataTable createInventoryItemsTable()
{
DataTable inv = new DataTable("inventoryitems");
createCol(inv, "UUID", typeof (String)); //inventoryID
createCol(inv, "assetID", typeof (String));
createCol(inv, "assetType", typeof (Int32));
createCol(inv, "invType", typeof (Int32));
createCol(inv, "parentFolderID", typeof (String));
createCol(inv, "avatarID", typeof (String));
createCol(inv, "creatorsID", typeof (String));
createCol(inv, "inventoryName", typeof (String));
createCol(inv, "inventoryDescription", typeof (String));
// permissions
createCol(inv, "inventoryNextPermissions", typeof (Int32));
createCol(inv, "inventoryCurrentPermissions", typeof (Int32));
createCol(inv, "inventoryBasePermissions", typeof (Int32));
createCol(inv, "inventoryEveryOnePermissions", typeof (Int32));
createCol(inv, "inventoryGroupPermissions", typeof (Int32));
// sale info
createCol(inv, "salePrice", typeof(Int32));
createCol(inv, "saleType", typeof(Byte));
// creation date
createCol(inv, "creationDate", typeof(Int32));
// group info
createCol(inv, "groupID", typeof(String));
createCol(inv, "groupOwned", typeof(Boolean));
// Flags
createCol(inv, "flags", typeof(UInt32));
inv.PrimaryKey = new DataColumn[] { inv.Columns["UUID"] };
return inv;
}
/// <summary>
/// Creates the "inventoryfolders" table
/// </summary>
/// <returns></returns>
private static DataTable createInventoryFoldersTable()
{
DataTable fol = new DataTable("inventoryfolders");
createCol(fol, "UUID", typeof (String)); //folderID
createCol(fol, "name", typeof (String));
createCol(fol, "agentID", typeof (String));
createCol(fol, "parentID", typeof (String));
createCol(fol, "type", typeof (Int32));
createCol(fol, "version", typeof (Int32));
fol.PrimaryKey = new DataColumn[] {fol.Columns["UUID"]};
return fol;
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupItemsCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryitems", ds.Tables["inventoryitems"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryitems", "UUID=:UUID", ds.Tables["inventoryitems"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryitems where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="da"></param>
/// <param name="conn"></param>
private void setupFoldersCommands(SqliteDataAdapter da, SqliteConnection conn)
{
lock (ds)
{
da.InsertCommand = createInsertCommand("inventoryfolders", ds.Tables["inventoryfolders"]);
da.InsertCommand.Connection = conn;
da.UpdateCommand = createUpdateCommand("inventoryfolders", "UUID=:UUID", ds.Tables["inventoryfolders"]);
da.UpdateCommand.Connection = conn;
SqliteCommand delete = new SqliteCommand("delete from inventoryfolders where UUID = :UUID");
delete.Parameters.Add(createSqliteParameter("UUID", typeof(String)));
delete.Connection = conn;
da.DeleteCommand = delete;
}
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <returns></returns>
private static InventoryFolderBase buildFolder(DataRow row)
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.ID = new UUID((string) row["UUID"]);
folder.Name = (string) row["name"];
folder.Owner = new UUID((string) row["agentID"]);
folder.ParentID = new UUID((string) row["parentID"]);
folder.Type = Convert.ToInt16(row["type"]);
folder.Version = Convert.ToUInt16(row["version"]);
return folder;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void fillFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["name"] = folder.Name;
row["agentID"] = folder.Owner.ToString();
row["parentID"] = folder.ParentID.ToString();
row["type"] = folder.Type;
row["version"] = folder.Version;
}
/// <summary>
///
/// </summary>
/// <param name="row"></param>
/// <param name="folder"></param>
private static void moveFolderRow(DataRow row, InventoryFolderBase folder)
{
row["UUID"] = folder.ID.ToString();
row["parentID"] = folder.ParentID.ToString();
}
public List<InventoryItemBase> fetchActiveGestures (UUID avatarID)
{
lock (ds)
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
DataTable inventoryItemTable = ds.Tables["inventoryitems"];
string selectExp
= "avatarID = '" + avatarID + "' AND assetType = " + (int)AssetType.Gesture + " AND flags = 1";
//m_log.DebugFormat("[SQL]: sql = " + selectExp);
DataRow[] rows = inventoryItemTable.Select(selectExp);
foreach (DataRow row in rows)
{
items.Add(buildItem(row));
}
return items;
}
}
}
}
| |
// Copyright (c) 2014 Thong Nguyen (tumtumtum@gmail.com)
using System;
using System.Threading;
namespace Platform
{
/// <summary>
/// Provides extension methods and static utility methods for <see cref="Action"/> objects.
/// </summary>
public static class ActionUtils<T>
{
public static readonly Action<T> Null = delegate { };
}
/// <summary>
/// Provides extension methods and static utility methods for <see cref="Action"/> objects.
/// </summary>
public static class ActionUtils
{
public static Func<T, R> ToFunc<T, R>(this Action<T> action)
{
return x => { action(x); return default(R); };
}
public static Func<T, T> ToFunc<T>(this Action<T> action)
{
return x => { action(x); return default(T); };
}
public static Func<T, R> ToFunc<T, R>(this Action<T> action, R result)
{
return x => { action(x); return result; };
}
public static Exception IgnoreExceptions(Action action)
{
try
{
action();
}
catch (Exception e)
{
return e;
}
return null;
}
/// <summary>
/// Executes an action and returns True if the action executes without throwing an exception.
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <returns>True if the action executed without throwing an exception</returns>
public static bool IsSuccess<T>(Action<T> action)
{
return IsSuccess(action, default(T));
}
/// <summary>
/// Executes an action and returns True if the action executes without throwing an exception.
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="state">The argument to be passed to the action</param>
/// <returns>True if the action executed without throwing an exception</returns>
public static bool IsSuccess<T>(Action<T> action, T state)
{
try
{
action(state);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, int repeatCount)
{
return ToRetryAction(action, repeatCount, TimeSpan.Zero);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.
/// </param>/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, TimeSpan maximumTime, Predicate<Exception> retryOnException)
{
return ToRetryAction(action, maximumTime, null, retryOnException);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, TimeSpan maximumTime, TimeSpan pause)
{
return ToRetryAction(action, maximumTime, pause, PredicateUtils<Exception>.AlwaysTrue);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">A predicate that will validate if the action should continue retrying after the given has been thrown</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, TimeSpan maximumTime, TimeSpan pause, Predicate<Exception> retryOnException)
{
return ToRetryAction(action, maximumTime, (TimeSpan?)pause, retryOnException);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.
/// </param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, TimeSpan maximumTime, TimeSpan? pause, Predicate<Exception> retryOnException)
{
DateTime startTime;
return delegate(T state)
{
startTime = DateTime.Now;
while (true)
{
try
{
action(state);
return;
}
catch (Exception e)
{
if (!retryOnException(e))
{
throw;
}
if (DateTime.Now - startTime > maximumTime)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(maximumTime.TotalSeconds / 10));
}
};
}
/// <summary>
/// Creates a new action an action and retries it a set number of times
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, int repeatCount, TimeSpan pause)
{
return ToRetryAction(action, repeatCount, (TimeSpan?)pause);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <typeparam name="T">The argument type for the action</typeparam>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action<T> ToRetryAction<T>(Action<T> action, int repeatCount, TimeSpan? pause)
{
return delegate(T state)
{
for (var i = 0; i < repeatCount; i++)
{
try
{
action(state);
return;
}
catch (Exception)
{
if (i == repeatCount - 1)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(0));
}
};
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, int repeatCount)
{
return ToRetryAction(action, repeatCount, TimeSpan.Zero);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.
/// </param>/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, TimeSpan maximumTime, Predicate<Exception> retryOnException)
{
return ToRetryAction(action, maximumTime, null, retryOnException);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, TimeSpan maximumTime, TimeSpan pause)
{
return ToRetryAction(action, maximumTime, pause, PredicateUtils<Exception>.AlwaysTrue);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">A predicate that will validate if the action should continue retrying after the given has been thrown</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, TimeSpan maximumTime, TimeSpan pause, Predicate<Exception> retryOnException)
{
return ToRetryAction(action, maximumTime, (TimeSpan?)pause, retryOnException);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.
/// </param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, TimeSpan maximumTime, TimeSpan? pause, Predicate<Exception> retryOnException)
{
DateTime startTime;
return delegate
{
startTime = DateTime.Now;
while (true)
{
try
{
action();
return;
}
catch (Exception e)
{
if (!retryOnException(e))
{
throw;
}
if (DateTime.Now - startTime > maximumTime)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(maximumTime.TotalSeconds / 10));
}
};
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, int repeatCount, TimeSpan pause)
{
return ToRetryAction(action, repeatCount, (TimeSpan?)pause);
}
/// <summary>
/// Returns an action that performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <returns>An action that wraps he given <see cref="action"/></returns>
public static Action ToRetryAction(Action action, int repeatCount, TimeSpan? pause)
{
return delegate
{
for (var i = 0; i < repeatCount; i++)
{
try
{
action();
return;
}
catch (Exception)
{
if (i == repeatCount - 1)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(0));
}
};
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
public static void RetryAction(Action action, int repeatCount)
{
RetryAction(action, repeatCount, TimeSpan.Zero);
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.</param>
public static void RetryAction(Action action, TimeSpan maximumTime, Predicate<Exception> retryOnException)
{
RetryAction(action, maximumTime, null, retryOnException);
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
public static void RetryAction(Action action, TimeSpan maximumTime, TimeSpan pause)
{
RetryAction(action, maximumTime, pause, PredicateUtils<Exception>.AlwaysTrue);
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">A predicate that will validate if the action should continue retrying after the given has been thrown</param>
public static void RetryAction(Action action, TimeSpan maximumTime, TimeSpan pause, Predicate<Exception> retryOnException)
{
RetryAction(action, maximumTime, (TimeSpan?)pause, retryOnException);
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="maximumTime">The maximum time to spend trying to execute the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
/// <param name="retryOnException">
/// A predicate that will validate if the action should continue retrying after the given has been thrown.
/// If the predicate does not return True then the exception will be thrown and no further retries will be performed.
/// </param>
public static void RetryAction(Action action, TimeSpan maximumTime, TimeSpan? pause, Predicate<Exception> retryOnException)
{
var startTime = DateTime.Now;
while (true)
{
try
{
action();
return;
}
catch (Exception e)
{
if (!retryOnException(e))
{
throw;
}
if (DateTime.Now - startTime > maximumTime)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(maximumTime.TotalSeconds / 10));
}
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
public static void RetryAction(Action action, int repeatCount, TimeSpan pause)
{
RetryAction(action, repeatCount, (TimeSpan?)pause);
}
/// <summary>
/// Performs an action a set number of times until it suceeds without an exception
/// </summary>
/// <param name="action">The action to execute</param>
/// <param name="repeatCount">The number of times to try executing the action</param>
/// <param name="pause">The amount of time to pause between retries</param>
public static void RetryAction(Action action, int repeatCount, TimeSpan? pause)
{
for (var i = 0; i < repeatCount; i++)
{
try
{
action();
return;
}
catch (Exception)
{
if (i == repeatCount - 1)
{
throw;
}
}
Thread.Sleep(pause ?? TimeSpan.FromSeconds(0));
}
}
}
}
| |
using System.Collections.Generic;
using Flame.Compiler;
using LLVMSharp;
using static LLVMSharp.LLVM;
namespace Flame.LLVM.Codegen
{
/// <summary>
/// A try-catch block implementation for the Itanium C++ ABI.
/// </summary>
public sealed class ItaniumCxxCatchBlock : CodeBlock
{
/// <summary>
/// Creates a try-catch block.
/// </summary>
/// <param name="CodeGenerator">The code generator that creates this block.</param>
/// <param name="TryBody">The body of the try clause.</param>
/// <param name="CatchClauses">The list of catch clauses.</param>
public ItaniumCxxCatchBlock(
ICodeGenerator CodeGenerator,
CodeBlock TryBody,
IReadOnlyList<CatchClause> CatchClauses)
{
this.codeGenerator = CodeGenerator;
this.TryBody = TryBody;
this.CatchClauses = CatchClauses;
}
/// <summary>
/// Gets the body of the try clause in this block.
/// </summary>
/// <returns>The try clause's body.</returns>
public CodeBlock TryBody { get; private set; }
/// <summary>
/// Gets a read-only list of catch clauses in this block.
/// </summary>
/// <returns>The list of catch clauses.</returns>
public IReadOnlyList<CatchClause> CatchClauses { get; private set; }
private ICodeGenerator codeGenerator;
/// <inheritdoc/>
public override ICodeGenerator CodeGenerator => codeGenerator;
/// <inheritdoc/>
public override IType Type => TryBody.Type;
/// <inheritdoc/>
public override BlockCodegen Emit(BasicBlockBuilder BasicBlock)
{
if (CatchClauses.Count == 0)
{
return TryBody.Emit(BasicBlock);
}
var exceptionDataType = StructType(new[] { PointerType(Int8Type(), 0), Int32Type() }, false);
var catchBlock = BasicBlock.CreateChildBlock("catch");
var catchLandingPadBlock = BasicBlock.CreateChildBlock("catch_landingpad");
var leaveBlock = BasicBlock.CreateChildBlock("leave");
// The try block is a regular block that jumps to the 'leave' block.
//
// try:
// <try body>
// br label %leave
var tryCodegen = TryBody.Emit(BasicBlock.WithUnwindTarget(catchLandingPadBlock, catchBlock));
BuildBr(tryCodegen.BasicBlock.Builder, leaveBlock.Block);
PopulateCatchBlock(catchBlock, leaveBlock);
ItaniumCxxFinallyBlock.PopulateThunkLandingPadBlock(catchLandingPadBlock, catchBlock.Block, false);
return new BlockCodegen(leaveBlock, tryCodegen.Value);
}
/// <summary>
/// Populates the given 'catch' block.
/// </summary>
/// <param name="CatchBlock">The 'catch' block to populate.</param>
/// <param name="LeaveBlock">The 'leave' block to jump to when the 'catch' is done.</param>
private void PopulateCatchBlock(BasicBlockBuilder CatchBlock, BasicBlockBuilder LeaveBlock)
{
var catchBlockEntry = CatchBlock;
// Before we even get started on the catch block's body, we should first
// take the time to ensure that the '__cxa_begin_catch' environment set up
// by the catch block is properly terminated by a '__cxa_end_catch' call,
// even if an exception is thrown from the catch block itself. We can do
// so by creating a 'catch_end' block and a thunk landing pad.
var catchEndBlock = CatchBlock.CreateChildBlock("catch_end");
var catchExceptionBlock = CatchBlock.CreateChildBlock("catch_exception");
var catchEndLandingPadBlock = CatchBlock.CreateChildBlock("catch_end_landingpad");
ItaniumCxxFinallyBlock.PopulateThunkLandingPadBlock(
catchEndLandingPadBlock,
catchExceptionBlock.Block,
true);
CatchBlock = CatchBlock.WithUnwindTarget(catchEndLandingPadBlock, catchEndBlock);
// The catch block starts like this:
//
// catch:
// %exception_data = load { i8*, i32 }* %exception_data_alloca
// %exception_obj = extractvalue { i8*, i32 } %exception_data, 0
// %exception_ptr_opaque = call i8* @__cxa_begin_catch(i8* %exception_obj)
// %exception_ptr = bitcast i8* %exception_ptr_opaque to i8**
// %exception = load i8*, i8** %exception_ptr
// %exception_vtable_ptr_ptr = bitcast i8* %exception to i8**
// %exception_vtable_ptr = load i8*, i8** %exception_vtable_ptr_ptr
// %exception_typeid = <typeid> i64, i8* %exception_vtable_ptr
var exceptionData = BuildLoad(
CatchBlock.Builder,
CatchBlock.FunctionBody.ExceptionDataStorage.Value,
"exception_data");
var exceptionObj = BuildExtractValue(
CatchBlock.Builder,
exceptionData,
0,
"exception_obj");
var exceptionPtrOpaque = BuildCall(
CatchBlock.Builder,
CatchBlock.FunctionBody.Module.Declare(IntrinsicValue.CxaBeginCatch),
new LLVMValueRef[] { exceptionObj },
"exception_ptr_opaque");
var exceptionPtr = BuildBitCast(
CatchBlock.Builder,
exceptionPtrOpaque,
PointerType(PointerType(Int8Type(), 0), 0),
"exception_ptr");
var exception = BuildLoad(CatchBlock.Builder, exceptionPtr, "exception");
var exceptionVtablePtrPtr = BuildBitCast(
CatchBlock.Builder,
exception,
PointerType(PointerType(Int8Type(), 0), 0),
"exception_vtable_ptr_ptr");
var exceptionVtablePtr = AtAddressEmitVariable.BuildConstantLoad(
CatchBlock.Builder,
exceptionVtablePtrPtr,
"exception_vtable_ptr");
var exceptionTypeid = TypeIdBlock.BuildTypeid(
CatchBlock.Builder,
exceptionVtablePtr);
// Next, we need to figure out if we have a catch block that can handle the
// exception we've thrown. We do so by iterating over all catch blocks and
// testing if they're a match for the exception's type.
var fallthroughBlock = CatchBlock.CreateChildBlock("catch_test");
for (int i = 0; i < CatchClauses.Count; i++)
{
var clause = CatchClauses[i];
var catchBodyBlock = CatchBlock.CreateChildBlock("catch_body");
var catchBodyBlockTail = catchBodyBlock;
// First, emit the catch body. This is just a regular block that
// clears the exception value variable when it gets started and
// jumps to the 'catch_end' when it's done.
//
// catch_body:
// %exception_val = bitcast i8* %exception to <clause_type>
// store <clause_type> %exception_val, <clause_type>* %clause_exception_variable_alloca
// <catch clause body>
// br catch_end
var ehVarAddressAndBlock = clause.LLVMHeader
.AtAddressExceptionVariable.Address.Emit(catchBodyBlockTail);
catchBodyBlockTail = ehVarAddressAndBlock.BasicBlock;
BuildStore(
catchBodyBlockTail.Builder,
BuildBitCast(
catchBodyBlockTail.Builder,
exception,
catchBodyBlockTail.FunctionBody.Module.Declare(clause.ExceptionType),
"exception_val"),
ehVarAddressAndBlock.Value);
catchBodyBlockTail = clause.Body.Emit(catchBodyBlockTail).BasicBlock;
BuildBr(catchBodyBlockTail.Builder, catchEndBlock.Block);
// Each clause is implemented as:
//
// catch_clause:
// %clause_typeid = <typeid> i64, clause-exception-type
// %typeid_rem = urem i64 %exception_typeid_tmp, %clause_typeid
// %is_subtype = cmp eq i64 %typeid_rem, 0
// br i1 %is_subtype, label %catch_body, label %fallthrough
//
var clauseTypeid = CatchBlock.FunctionBody.Module.GetTypeId((LLVMType)clause.ExceptionType);
var typeIdRem = BuildURem(
CatchBlock.Builder,
exceptionTypeid,
ConstInt(exceptionTypeid.TypeOf(), clauseTypeid, false),
"typeid_rem");
var isSubtype = BuildICmp(
CatchBlock.Builder,
LLVMIntPredicate.LLVMIntEQ,
typeIdRem,
ConstInt(exceptionTypeid.TypeOf(), 0, false),
"is_subtype");
BuildCondBr(CatchBlock.Builder, isSubtype, catchBodyBlock.Block, fallthroughBlock.Block);
CatchBlock = fallthroughBlock;
fallthroughBlock = CatchBlock.CreateChildBlock("catch_test");
}
// If we didn't match any catch clauses, then we'll rethrow the exception and
// unwind to the end-catch landing pad.
//
// no_matching_clause:
// invoke void @__cxa_rethrow() to label %unreachable unwind label %catch_end_landingpad
//
// unreachable:
// unreachable
BuildInvoke(
CatchBlock.Builder,
CatchBlock.FunctionBody.Module.Declare(IntrinsicValue.CxaRethrow),
new LLVMValueRef[] { },
fallthroughBlock.Block,
catchEndLandingPadBlock.Block,
"");
BuildUnreachable(fallthroughBlock.Builder);
// The catch end block simply calls '__cxa_end_catch' and jumps to the 'leave'
// block. Like so:
//
// catch_end:
// call void @__cxa_end_catch()
// br label %leave
BuildCall(
catchEndBlock.Builder,
CatchBlock.FunctionBody.Module.Declare(IntrinsicValue.CxaEndCatch),
new LLVMValueRef[] { },
"");
BuildBr(catchEndBlock.Builder, LeaveBlock.Block);
// The 'catch exception' block is entered when an exception is thrown from
// the 'catch' block, or if the catch block is ill-equipped to handle the
// exception. Its responsibility is to end the catch block and jump to
// the manual unwind target.
//
// catch_exception:
// call void @__cxa_end_catch()
// br label %manual_unwind_target
BuildCall(
catchExceptionBlock.Builder,
catchExceptionBlock.FunctionBody.Module.Declare(IntrinsicValue.CxaEndCatch),
new LLVMValueRef[] { },
"");
BuildBr(catchExceptionBlock.Builder, ItaniumCxxFinallyBlock.GetManualUnwindTarget(catchBlockEntry));
}
}
}
| |
// Copyright (c) Alexandre Mutel. All rights reserved.
// Licensed under the BSD-Clause 2 license.
// See license.txt file in the project root for full license information.
#nullable disable
using System;
using System.Collections.Generic;
namespace Scriban.Syntax
{
#if SCRIBAN_PUBLIC
public
#else
internal
#endif
static class ScriptNodeExtensions
{
public static ScriptNode FindFirstTerminal(this ScriptNode node)
{
if (node == null) return null;
if (node is IScriptTerminal)
{
return node;
}
var count = node.ChildrenCount;
for (int i = 0; i < count; i++)
{
var child = node.GetChildren(i);
if (child != null)
{
// TODO: could be optimized with a stack
var first = FindFirstTerminal(child);
if (first != null)
{
return first;
}
}
}
return null;
}
public static ScriptNode FindLastTerminal(this ScriptNode node)
{
if (node == null) return null;
if (node is IScriptTerminal)
{
return node;
}
var count = node.ChildrenCount;
for (int i = count - 1; i >= 0; i--)
{
var child = node.GetChildren(i);
if (child != null)
{
// TODO: could be optimized with a stack
var last = FindLastTerminal(child);
if (last != null)
{
return last;
}
}
}
return null;
}
public static T RemoveLeadingSpace<T>(this T node) where T : ScriptNode
{
var firstTerminal = (IScriptTerminal)FindFirstTerminal(node);
var trivias = firstTerminal?.Trivias;
if (trivias != null)
{
var triviasBefore = trivias.Before;
if (triviasBefore.Count > 0)
{
for (int i = 0; i < triviasBefore.Count; i++)
{
var trivia = triviasBefore[i];
if (trivia.Type.IsSpaceOrNewLine())
{
triviasBefore.RemoveAt(i);
i--;
}
else
{
break;
}
}
}
}
return node;
}
public static T RemoveTrailingSpace<T>(this T node) where T : ScriptNode
{
var lastTerminal = (IScriptTerminal)FindLastTerminal(node);
var trivias = lastTerminal?.Trivias;
if (trivias != null)
{
var triviasAfter = trivias.After;
if (triviasAfter.Count > 0)
{
for (var i = triviasAfter.Count - 1; i >= 0; i--)
{
var trivia = triviasAfter[i];
if (trivia.Type.IsSpaceOrNewLine())
{
triviasAfter.RemoveAt(i);
}
else
{
break;
}
}
}
}
return node;
}
public static void MoveLeadingTriviasTo<T>(this ScriptNode node, T destinationNode) where T : ScriptNode, IScriptTerminal
{
var firstTerminal = (IScriptTerminal)node.FindFirstTerminal();
var trivias = firstTerminal?.Trivias;
if (trivias != null)
{
var before = trivias.Before;
foreach (var trivia in before)
{
destinationNode.AddTrivia(trivia, true);
}
before.Clear();
}
}
public static void MoveTrailingTriviasTo<T>(this ScriptNode node, T destinationNode, bool before) where T : ScriptNode, IScriptTerminal
{
var lastTerminal = (IScriptTerminal)node.FindLastTerminal();
var trivias = lastTerminal?.Trivias;
if (trivias != null)
{
var after = trivias.After;
if (before)
{
for (var i = after.Count - 1; i >= 0; i--)
{
var trivia = after[i];
destinationNode.InsertTrivia(trivia, false);
}
}
else
{
foreach (var trivia in after)
{
destinationNode.AddTrivia(trivia, false);
}
}
after.Clear();
}
}
public static void AddLeadingSpace(this IScriptTerminal node)
{
if (!node.HasLeadingSpaceTrivias())
{
node.AddTrivia(ScriptTrivia.Space, true);
}
}
public static void AddCommaAfter(this IScriptTerminal node)
{
if (!node.HasTrivia(ScriptTriviaType.Comma, false))
{
node.AddTrivia(ScriptTrivia.Comma, false);
}
}
public static void AddSemiColonAfter(this IScriptTerminal node)
{
if (!node.HasTrivia(ScriptTriviaType.SemiColon, false))
{
node.AddTrivia(ScriptTrivia.SemiColon, false);
}
}
public static void AddSpaceAfter(this IScriptTerminal node)
{
if (!node.HasTrailingSpaceTrivias())
{
node.AddTrivia(ScriptTrivia.Space, false);
}
}
public static void AddTrivia(this IScriptTerminal node, ScriptTrivia trivia, bool before)
{
var trivias = node.Trivias;
if (trivias == null)
{
node.Trivias = trivias = new ScriptTrivias();
}
(before ? trivias.Before : trivias.After).Add(trivia);
}
public static void InsertTrivia(this IScriptTerminal node, ScriptTrivia trivia, bool before)
{
var trivias = node.Trivias;
if (trivias == null)
{
node.Trivias = trivias = new ScriptTrivias();
}
(before ? trivias.Before : trivias.After).Insert(0, trivia);
}
public static void AddTrivias<T>(this IScriptTerminal node, T trivias, bool before) where T : IEnumerable<ScriptTrivia>
{
foreach (var trivia in trivias)
{
node.AddTrivia(trivia, before);
}
}
public static bool HasLeadingSpaceTrivias(this IScriptTerminal node)
{
if (node.Trivias == null)
{
return false;
}
foreach (var trivia in node.Trivias.Before)
{
if (trivia.Type.IsSpaceOrNewLine())
{
return true;
}
else
{
break;
}
}
return false;
}
public static bool HasTrailingSpaceTrivias(this IScriptTerminal node)
{
if (node.Trivias == null)
{
return false;
}
var triviasAfter = node.Trivias.After;
if (triviasAfter.Count > 0)
{
var trivia = triviasAfter[triviasAfter.Count - 1];
if (trivia.Type.IsSpaceOrNewLine())
{
return true;
}
}
return false;
}
public static bool HasTrivia(this IScriptTerminal node, ScriptTriviaType triviaType, bool before)
{
if (node.Trivias == null)
{
return false;
}
foreach (var trivia in (before ? node.Trivias.Before : node.Trivias.After))
{
if (trivia.Type == triviaType)
{
return true;
}
}
return false;
}
public static bool HasTriviaEndOfStatement(this IScriptTerminal node, bool before)
{
if (node.Trivias == null)
{
return false;
}
foreach (var trivia in (before ? node.Trivias.Before : node.Trivias.After))
{
if (trivia.Type == ScriptTriviaType.NewLine || trivia.Type == ScriptTriviaType.SemiColon)
{
return true;
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Signum.Engine.Maps;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Engine.Basics;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Entities;
using Signum.Engine.Operations;
using System.Reflection;
using System.Xml.Linq;
namespace Signum.Engine.Authorization
{
public static class OperationAuthLogic
{
static AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed> cache = null!;
public static HashSet<OperationSymbol> AvoidCoerce = new HashSet<OperationSymbol>();
public static IManualAuth<(OperationSymbol operation, Type type), OperationAllowed> Manual { get { return cache; } }
public static bool IsStarted { get { return cache != null; } }
public static readonly Dictionary<OperationSymbol, OperationAllowed> MaxAutomaticUpgrade = new Dictionary<OperationSymbol, OperationAllowed>();
internal static readonly string operationReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
AuthLogic.AssertStarted(sb);
OperationLogic.AssertStarted(sb);
OperationLogic.AllowOperation += OperationLogic_AllowOperation;
sb.Include<RuleOperationEntity>()
.WithUniqueIndex(rt => new { rt.Resource.Operation, rt.Resource.Type, rt.Role });
cache = new AuthCache<RuleOperationEntity, OperationAllowedRule, OperationTypeEmbedded, (OperationSymbol operation, Type type), OperationAllowed>(sb,
toKey: s => (operation: s.Operation, type: s.Type.ToType()),
toEntity: s => new OperationTypeEmbedded { Operation = s.operation, Type = s.type.ToTypeEntity() },
isEquals: (o1, o2) => o1.Operation == o2.Operation && o1.Type == o2.Type,
merger: new OperationMerger(),
invalidateWithTypes: true,
coercer: OperationCoercer.Instance);
sb.Schema.EntityEvents<RoleEntity>().PreUnsafeDelete += query =>
{
Database.Query<RuleOperationEntity>().Where(r => query.Contains(r.Role.Entity)).UnsafeDelete();
return null;
};
AuthLogic.ExportToXml += exportAll => cache.ExportXml("Operations", "Operation", s => s.operation.Key + "/" + s.type?.ToTypeEntity().CleanName, b => b.ToString(),
exportAll ? AllOperationTypes() : null);
AuthLogic.ImportFromXml += (x, roles, replacements) =>
{
var allResources = x.Element("Operations").Elements("Role").SelectMany(r => r.Elements("Operation")).Select(p => p.Attribute("Resource").Value).ToHashSet();
replacements.AskForReplacements(
allResources.Select(a => a.TryBefore("/") ?? a).ToHashSet(),
SymbolLogic<OperationSymbol>.AllUniqueKeys(),
operationReplacementKey);
string typeReplacementKey = "AuthRules:" + typeof(OperationSymbol).Name;
replacements.AskForReplacements(
allResources.Select(a => a.After("/")).ToHashSet(),
TypeLogic.NameToType.Keys.ToHashSet(),
TypeAuthCache.typeReplacementKey);
return cache.ImportXml(x, "Operations", "Operation", roles,
s => {
var operation = SymbolLogic<OperationSymbol>.TryToSymbol(replacements.Apply(operationReplacementKey, s.Before("/")));
var type = TypeLogic.TryGetType(replacements.Apply(TypeAuthCache.typeReplacementKey, s.After("/")));
if (operation == null || type == null || !OperationLogic.IsDefined(type, operation))
return null;
return new OperationTypeEmbedded { Operation = operation, Type = type.ToTypeEntity() };
}, EnumExtensions.ToEnum<OperationAllowed>);
};
sb.Schema.Table<OperationSymbol>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteOperationSqlSync);
sb.Schema.Table<TypeEntity>().PreDeleteSqlSync += new Func<Entity, SqlPreCommand>(AuthCache_PreDeleteTypeSqlSync);
}
}
static SqlPreCommand AuthCache_PreDeleteOperationSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Operation, (OperationSymbol)arg);
}
static SqlPreCommand AuthCache_PreDeleteTypeSqlSync(Entity arg)
{
return Administrator.DeleteWhereScript((RuleOperationEntity rt) => rt.Resource.Type, (TypeEntity)arg);
}
public static T SetMaxAutomaticUpgrade<T>(this T operation, OperationAllowed allowed) where T : IOperation
{
MaxAutomaticUpgrade.Add(operation.OperationSymbol, allowed);
return operation;
}
static bool OperationLogic_AllowOperation(OperationSymbol operationKey, Type entityType, bool inUserInterface)
{
return GetOperationAllowed(operationKey, entityType, inUserInterface);
}
public static OperationRulePack GetOperationRules(Lite<RoleEntity> role, TypeEntity typeEntity)
{
var entityType = typeEntity.ToType();
var resources = OperationLogic.GetAllOperationInfos(entityType).Select(a => new OperationTypeEmbedded { Operation = a.OperationSymbol, Type = typeEntity });
var result = new OperationRulePack { Role = role, Type = typeEntity, };
cache.GetRules(result, resources);
var coercer = OperationCoercer.Instance.GetCoerceValue(role);
result.Rules.ForEach(r =>
{
var operationType = (operation: r.Resource.Operation, type: r.Resource.Type.ToType());
r.CoercedValues = EnumExtensions.GetValues<OperationAllowed>().Where(a => !coercer(operationType, a).Equals(a)).ToArray();
});
return result;
}
public static void SetOperationRules(OperationRulePack rules)
{
cache.SetRules(rules, r => r.Type == rules.Type);
}
public static bool GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType, bool inUserInterface)
{
OperationAllowed allowed = GetOperationAllowed(role, operation, entityType);
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static OperationAllowed GetOperationAllowed(Lite<RoleEntity> role, OperationSymbol operation, Type entityType)
{
return cache.GetAllowed(role, (operation, entityType));
}
public static bool GetOperationAllowed(OperationSymbol operation, Type type, bool inUserInterface)
{
if (!AuthLogic.IsEnabled || ExecutionMode.InGlobal)
return true;
if (GetTemporallyAllowed(operation))
return true;
OperationAllowed allowed = cache.GetAllowed(RoleEntity.Current, (operation, type));
return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface;
}
public static AuthThumbnail? GetAllowedThumbnail(Lite<RoleEntity> role, Type entityType)
{
return OperationLogic.GetAllOperationInfos(entityType).Select(oi => cache.GetAllowed(role, (oi.OperationSymbol, entityType))).Collapse();
}
public static Dictionary<(OperationSymbol operation, Type type), OperationAllowed> AllowedOperations()
{
return AllOperationTypes().ToDictionary(a => a, a => cache.GetAllowed(RoleEntity.Current, a));
}
static List<(OperationSymbol operation, Type type)> AllOperationTypes()
{
return (from type in Schema.Current.Tables.Keys
from o in OperationLogic.TypeOperations(type)
select (operation: o.OperationSymbol, type: type))
.ToList();
}
static readonly Variable<ImmutableStack<OperationSymbol>> tempAllowed = Statics.ThreadVariable<ImmutableStack<OperationSymbol>>("authTempOperationsAllowed");
public static IDisposable AllowTemporally(OperationSymbol operationKey)
{
tempAllowed.Value = (tempAllowed.Value ?? ImmutableStack<OperationSymbol>.Empty).Push(operationKey);
return new Disposable(() => tempAllowed.Value = tempAllowed.Value.Pop());
}
internal static bool GetTemporallyAllowed(OperationSymbol operationKey)
{
var ta = tempAllowed.Value;
if (ta == null || ta.IsEmpty)
return false;
return ta.Contains(operationKey);
}
public static void RegisterAvoidCoerce(this IOperation operation)
{
SetAvoidCoerce(operation.OperationSymbol);
operation.Register();
}
private static void SetAvoidCoerce(OperationSymbol operationSymbol)
{
AvoidCoerce.Add(operationSymbol);
}
public static OperationAllowed MaxTypePermission((OperationSymbol operation, Type type) operationType, TypeAllowedBasic checkFor, Func<Type, TypeAllowedAndConditions> allowed)
{
Func<Type, OperationAllowed> operationAllowed = t =>
{
if (!TypeLogic.TypeToEntity.ContainsKey(t))
return OperationAllowed.Allow;
var ta = allowed(t);
return checkFor <= ta.MaxUI() ? OperationAllowed.Allow :
checkFor <= ta.MaxDB() ? OperationAllowed.DBOnly :
OperationAllowed.None;
};
var operation = OperationLogic.FindOperation(operationType.type ?? /*Temp*/ OperationLogic.FindTypes(operationType.operation).First(), operationType.operation);
Type resultType = operation.OperationType == OperationType.ConstructorFrom ||
operation.OperationType == OperationType.ConstructorFromMany ? operation.ReturnType! : operation.OverridenType;
var result = operationAllowed(resultType);
if (result == OperationAllowed.None)
return result;
Type? fromType = operation.OperationType == OperationType.ConstructorFrom ||
operation.OperationType == OperationType.ConstructorFromMany ? operation.OverridenType : null;
if (fromType == null)
return result;
var fromTypeAllowed = operationAllowed(fromType);
return result < fromTypeAllowed ? result : fromTypeAllowed;
}
}
class OperationMerger : IMerger<(OperationSymbol operation, Type type), OperationAllowed>
{
public OperationAllowed Merge((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role, IEnumerable<KeyValuePair<Lite<RoleEntity>, OperationAllowed>> baseValues)
{
OperationAllowed best = AuthLogic.GetMergeStrategy(role) == MergeStrategy.Union ?
Max(baseValues.Select(a => a.Value)):
Min(baseValues.Select(a => a.Value));
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return best;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(operationType.Item1);
if (maxUp.HasValue && maxUp <= best)
return best;
if (baseValues.Where(a => a.Value.Equals(best)).All(a => GetDefault(operationType, a.Key).Equals(a.Value)))
{
var def = GetDefault(operationType, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
}
return best;
}
static OperationAllowed GetDefault((OperationSymbol operation, Type type) operationType, Lite<RoleEntity> role)
{
return OperationAuthLogic.MaxTypePermission(operationType, TypeAllowedBasic.Write, t => TypeAuthLogic.GetAllowed(role, t));
}
static OperationAllowed Max(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.None;
foreach (var item in baseValues)
{
if (item > result)
result = item;
if (result == OperationAllowed.Allow)
return result;
}
return result;
}
static OperationAllowed Min(IEnumerable<OperationAllowed> baseValues)
{
OperationAllowed result = OperationAllowed.Allow;
foreach (var item in baseValues)
{
if (item < result)
result = item;
if (result == OperationAllowed.None)
return result;
}
return result;
}
public Func<(OperationSymbol operation, Type type), OperationAllowed> MergeDefault(Lite<RoleEntity> role)
{
return key =>
{
if (AuthLogic.GetDefaultAllowed(role))
return OperationAllowed.Allow;
if (!BasicPermission.AutomaticUpgradeOfOperations.IsAuthorized(role))
return OperationAllowed.None;
var maxUp = OperationAuthLogic.MaxAutomaticUpgrade.TryGetS(key.operation);
var def = GetDefault(key, role);
return maxUp.HasValue && maxUp <= def ? maxUp.Value : def;
};
}
}
class OperationCoercer : Coercer<OperationAllowed, (OperationSymbol symbol, Type type)>
{
public static readonly OperationCoercer Instance = new OperationCoercer();
private OperationCoercer()
{
}
public override Func<(OperationSymbol symbol, Type type), OperationAllowed, OperationAllowed> GetCoerceValue(Lite<RoleEntity> role)
{
return (operationType, allowed) =>
{
if (OperationAuthLogic.AvoidCoerce.Contains(operationType.symbol))
return allowed;
var required = OperationAuthLogic.MaxTypePermission(operationType, TypeAllowedBasic.Read, t => TypeAuthLogic.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
public override Func<Lite<RoleEntity>, OperationAllowed, OperationAllowed> GetCoerceValueManual((OperationSymbol symbol, Type type) operationType)
{
return (role, allowed) =>
{
if (OperationAuthLogic.AvoidCoerce.Contains(operationType.symbol))
return allowed;
var required = OperationAuthLogic.MaxTypePermission(operationType, TypeAllowedBasic.Read, t => TypeAuthLogic.Manual.GetAllowed(role, t));
return allowed < required ? allowed : required;
};
}
}
}
| |
//----------------------------------------------------------------------//
// ___ ___ ___ ___ ___ ___ ________ ________ //
// |\ \ |\ \ / /|\ \ / /|\ \|\ ___ \|\ ____\ //
// \ \ \ \ \ \/ / | \ \ / / | \ \ \ \\ \ \ \ \___|_ //
// \ \ \ \ \ / / \ \ \/ / / \ \ \ \ \\ \ \ \_____ \ //
// \ \ \____ \/ / / \ \ / / \ \ \ \ \\ \ \|____|\ \ //
// \ \_______\__/ / / \ \__/ / \ \__\ \__\\ \__\____\_\ \ //
// \|_______|\___/ / \|__|/ \|__|\|__| \|__|\_________\//
// \|___|/ \|_________|//
// //
//----------------------------------------------------------------------//
// File : LyvinDevice.cs //
// Description : //
// Original author : J.Klessens //
// Company : Lyvins //
// Project : LyvinObjectsLib //
// Created on : 17-5-2014 //
//----------------------------------------------------------------------//
// //
// Copyright (c) 2013, 2014 Lyvins //
// //
// 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. //
// //
//----------------------------------------------------------------------//
// //
// Prerequisites / Return Codes / Notes //
// //
//----------------------------------------------------------------------//
// //
// Tasks / Features / Bugs //
// //
//----------------------------------------------------------------------//
using System;
using System.Collections.Generic;
using LyvinDeviceDriverLib;
using LyvinObjectsLib.Events;
namespace LyvinObjectsLib.Devices
{
// ToDo: Use protected, virtual and override to improve the code (see stackoverflow post)
// ToDo: Make it so this class can be serialized and deserialized, either by implementing OnSerializing and OnDeserializing method. Or by creating a dummy class with strings representing the zones, groups, etc...
public class LyvinDevice
{
public LyvinDevice()
{
DeviceList = new List<LyvinDevice>();
DeviceGroups = new List<DeviceGroup>();
DeviceTypes = new List<DeviceType>();
DeviceZones = new List<DeviceZone>();
Reachable = true;
Status = "ON";
}
/// <summary>
/// A constructor for a standard device.
/// </summary>
/// <param name="id">The unique id of the device</param>
/// <param name="name">The name of the device</param>
/// <param name="description">A description of the device</param>
/// <param name="deviceList">An optional list of sub devices if the device acts as a hub</param>
/// <param name="driver">The PDD of the device</param>
/// <param name="driverFile">The filename of the PDD</param>
/// <param name="type">The type of the device</param>
/// <param name="wattage">The wattage of the device</param>
/// <param name="deviceSettingsFile">The file name of the device settings file</param>
/// <param name="deviceSettingsType">The object type of the device settings used in (de)serialization</param>
/// <param name="deviceSettings">The object used by the pdd to store device settings</param>
/// <param name="reachable">a status indicator indicating whether the device is reachable</param>
/// <param name="status">The status of a device (ie ON/OFF/AUTO/MANUAL/etc.</param>
public LyvinDevice(string id, string name, string description, List<LyvinDevice> deviceList,
IPhysicalDeviceDriver driver, string driverFile, string type, int wattage,
string deviceSettingsFile, Type deviceSettingsType, object deviceSettings, bool reachable,
string status)
{
ID = id;
Name = name;
Description = description;
DeviceList = deviceList;
Driver = driver;
DriverFile = driverFile;
Type = type;
Wattage = wattage;
DeviceSettingsType = deviceSettingsType;
DeviceSettingsFile = deviceSettingsFile;
DeviceGroups = new List<DeviceGroup>();
DeviceTypes = new List<DeviceType>();
DeviceZones = new List<DeviceZone>();
DeviceSettings = deviceSettings;
Reachable = reachable;
Status = status;
}
/// <summary>
/// A description of the device
/// </summary>
public string Description { get; set; }
/// <summary>
/// An optional list of sub devices if the device acts as a hub
/// </summary>
public List<LyvinDevice> DeviceList { get; set; }
/// <summary>
/// The PDD of the device
/// </summary>
public IPhysicalDeviceDriver Driver { get; set; }
/// <summary>
/// The filename of the PDD
/// </summary>
public string DriverFile { get; set; }
/// <summary>
/// The object used by the pdd to store device settings
/// </summary>
public object DeviceSettings { get; set; }
/// <summary>
/// The filename of the device settings file to which the device settings object will be parsed
/// </summary>
public string DeviceSettingsFile { get; set; }
/// <summary>
/// The unique ID of the device
/// </summary>
public string ID { get; set; }
/// <summary>
/// The name of the device
/// </summary>
public string Name { get; set; }
/// <summary>
/// The wattage of the device
/// </summary>
public int Wattage { get; set; }
/// <summary>
/// The type of the device
/// </summary>
public string Type { get; set; }
/// <summary>
/// The object type of the device settings used in (de)serialization
/// </summary>
public Type DeviceSettingsType { get; set; }
/// <summary>
/// The Device Zones a device is part of.
/// </summary>
public List<DeviceZone> DeviceZones { get; set; }
/// <summary>
/// The Device groups a device is part of.
/// </summary>
public List<DeviceGroup> DeviceGroups { get; set; }
/// <summary>
/// The device types a device is part of.
/// </summary>
public List<DeviceType> DeviceTypes { get; set; }
/// <summary>
/// Whether a device is reachable or not.
/// </summary>
public bool Reachable { get; set; }
/// <summary>
/// The status of a device (ie ON/OFF/AUTO/MANUAL/etc.
/// </summary>
public string Status { get; set; }
public virtual void ReceiveDeviceEvent(LyvinEvent deviceEvent)
{
if (deviceEvent.SourceID == ID)
{
switch (deviceEvent.Code)
{
case "DEVICE_STATUS":
Status = string.Copy(deviceEvent.Value);
break;
case "DEVICE_REACHABLE":
Reachable = deviceEvent.Value == "True";
break;
default:
break;
}
}
}
public virtual string GetDeviceValue(string attribute)
{
switch (attribute)
{
case "STATUS":
return Status;
case "REACHABLE":
return Reachable.ToString();
default:
return "";
}
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: logicmoo@gmail.com
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*********************************************************/
#if USE_MUSHDLR
using MushDLR223.Utilities;
#endif
using org.jpl7;
#if USE_IKVM
//using JClass = java.lang.JClass;
#else
using JClass = System.Type;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using SbsSW.SwiPlCs;
using PlTerm = SbsSW.SwiPlCs.PlTerm;
using OBJ_TO_OBJ = System.Func<object, object>;
namespace Swicli.Library
{
/* public delegate void Action();
public delegate void Action<T>(T arg);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func_22<T, TResult>(T arg);
public delegate object OBJ_TO_OBJ(object from);
*/
public partial class PrologCLR
{
[PrologVisible]
static public bool cliCast(PlTerm valueIn, PlTerm clazzSpec, PlTerm valueOut)
{
if (!valueOut.IsVar)
{
var plvar = PlTerm.PlVar();
return cliCast(valueIn, clazzSpec, plvar) && SpecialUnify(valueOut, plvar);
}
Type type = GetType(clazzSpec);
if (type == null)
{
return Embedded.Error("Cant find class {0}", clazzSpec);
}
if (valueIn.IsVar)
{
return Embedded.Error("Cant find instance {0}", valueIn);
}
object retval = CastTerm(valueIn, type);
return UnifyTagged(retval, valueOut);
}
[PrologVisible]
static public bool cliCastImmediate(PlTerm valueIn, PlTerm clazzSpec, PlTerm valueOut)
{
if (valueIn.IsVar)
{
return Embedded.Warn("Cant find instance {0}", valueIn);
}
if (!valueOut.IsVar)
{
var plvar = PlTerm.PlVar();
return cliCastImmediate(valueIn, clazzSpec, plvar) && SpecialUnify(valueOut, plvar);
}
Type type = GetType(clazzSpec);
object retval = CastTerm(valueIn, type);
return valueOut.FromObject(retval);
}
public static Object CastTerm(PlTerm o, Type pt)
{
if (pt == typeof(object)) pt = null;
object r = CastTerm0(o, pt);
if (pt == null || r == null)
return r;
Type fr = r.GetType();
if (pt.IsInstanceOfType(r)) return r;
return RecastObject(pt, r, fr);
}
public static readonly Dictionary<string, List<OBJ_TO_OBJ>> convertCache =
new Dictionary<string, List<OBJ_TO_OBJ>>();
public static object RecastObject(Type pt, object r, Type fr)
{
Exception ce = null;
try
{
if (r is double && pt == typeof(float))
{
double d = (double)r;
return Convert.ToSingle(d);
}
}
catch (InvalidCastException e)
{
Embedded.Debug("conversion {0} to {1} resulted in {2}", fr, pt, e);
ce = e;
}
catch (Exception e)
{
Embedded.Debug("conversion {0} to {1} resulted in {2}", fr, pt, e);
ce = e;
}
try
{
var tryAll = GetConvertCache(fr, pt);
if (tryAll != null && tryAll.Count > 0)
{
ce = null;
int wn = 0;
bool somethingWorked = false;
object retVal = null;
foreach (var ti in tryAll)
{
try
{
retVal = ti(r);
somethingWorked = true;
if (pt.IsInstanceOfType(retVal))
{
if (wn != 0)
{
// put this conversion method first in list
tryAll.RemoveAt(wn);
tryAll.Insert(0, ti);
}
return retVal;
}
}
catch (Exception ee)
{
ce = ce ?? ee;
}
wn++;
}
if (somethingWorked)
{
// probly was a null->null conversion
return retVal;
}
}
}
catch (Exception e)
{
Embedded.Debug("conversion {0} to {1} resulted in {2}", fr, pt, e);
ce = ce ?? e;
}
Embedded.Warn("Having a time converting {0} to {1} why {2}", r, pt, ce);
return r;
}
private static List<OBJ_TO_OBJ> GetConvertCache(Type from, Type to)
{
string key = "" + @from + "->" + to;
List<OBJ_TO_OBJ> found;
bool wasNew = true;
lock (convertCache)
{
wasNew = !convertCache.TryGetValue(key, out found);
if (wasNew)
{
found = convertCache[key] = new List<OBJ_TO_OBJ>();
}
}
if (wasNew)
{
findConversions(@from, to, found);
}
return found;
}
private static void registerConversion(MethodInfo converterMethod, Type from, Type to)
{
int fromArg = 0;
if (to == null)
{
to = converterMethod.ReturnType;
}
if (@from == null)
{
@from = (converterMethod.GetParameters()[fromArg]).ParameterType;
}
OBJ_TO_OBJ meth = (a) => converterMethod.Invoke(null, new[] { a });
string key = "" + @from + "->" + to;
List<OBJ_TO_OBJ> found;
bool wasNew = true;
lock (convertCache)
{
wasNew = !convertCache.TryGetValue(key, out found);
if (wasNew)
{
found = convertCache[key] = new List<OBJ_TO_OBJ>();
}
found.Add(meth);
}
}
private static readonly List<Type> ConvertorClasses = new List<Type>();
public static T ReflectiveCast<T>(object o)
{
T t = (T) o;
return t;
}
public static T ReflectiveNull<T>()
{
T t = default(T);
return t;
}
private static void CheckMI()
{
if (MissingMI == null)
{
MissingMI = typeof(PrologCLR).GetMethod("ReflectiveCast", BindingFlagsJustStatic);
}
if (MakeDefaultViaReflectionInfo == null)
{
MakeDefaultViaReflectionInfo = typeof(PrologCLR).GetMethod("ReflectiveNull", BindingFlagsJustStatic);
}
}
private static OBJ_TO_OBJ findConversions(Type from, Type to, ICollection<OBJ_TO_OBJ> allMethods)
{
OBJ_TO_OBJ meth;
if (to.IsAssignableFrom(@from))
{
meth = (r) => r;
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
OBJ_TO_OBJ sysmeth = (r) =>
{
CheckMI();
if (r == null)
{
MethodInfo rc = MakeDefaultViaReflectionInfo.MakeGenericMethod(to);
return rc.Invoke(null, ZERO_OBJECTS);
}
else
{
MethodInfo rc = MissingMI.MakeGenericMethod(to);
return rc.Invoke(null, new[] { r });
}
};
if (to.IsValueType)
{
if (allMethods != null) allMethods.Add(sysmeth);
else
{
// dont return .. this is the fallthru at bottem anyhow
// return sysmeth;
}
}
if (to.IsEnum)
{
meth = (r) =>
{
if (r == null)
{
return null;
}
string rs = r.ToString();
if (rs.Length == 0) return null;
return Enum.Parse(to, rs);
};
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
if (to.IsPrimitive)
{
meth = ((r) => Convert.ChangeType(r, to));
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
if (to.IsArray && @from.IsArray)
{
var eto = to.GetElementType();
var efrom = @from.GetElementType();
meth = ((r) =>
{
Array ar = ((Array)r);
int len = ar.Length;
Array ret = Array.CreateInstance(eto, len);
for (int i = 0; i < len; i++)
{
ret.SetValue(RecastObject(eto, ar.GetValue(i), efrom), i);
}
return ret;
});
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
ConstructorInfo ci = to.GetConstructor(new Type[] { @from });
if (ci != null)
{
meth = (r) => ci.Invoke(new object[] { r });
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
ConstructorInfo pc = null;
foreach (ConstructorInfo mi in to.GetConstructors(BindingFlagsALL))
{
var ps = mi.GetParameters();
if (ps.Length == 0 && !mi.IsStatic)
{
pc = mi;
continue;
}
if (ps.Length == 1)
{
Type pt = ps[0].ParameterType;
if (pt.IsAssignableFrom(@from))
{
ConstructorInfo info = mi;
meth = (r) => info.Invoke(new object[] { r });
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
}
}
// search for op_Implicit/Explicit
var someStatic = SomeConversionStaticMethod(to, to, @from, allMethods, false);
if (someStatic != null) return someStatic;
// search for op_Implicit/Explicit
someStatic = SomeConversionStaticMethod(to, @from, @from, allMethods, false);
if (someStatic != null) return someStatic;
if (ConvertorClasses.Count == 0)
{
cliRegisterConvertor(typeof(Convert),false);
cliRegisterConvertor(typeof(PrologConvert),true);
//ConvertorClasses.Add(typeof(PrologCLR));
}
foreach (Type convertorClasse in ConvertorClasses)
{
var someStaticM = SomeConversionStaticMethod(to, convertorClasse, @from, allMethods, false);
if (someStaticM != null) return someStatic;
}
//if (PrologBinder.CanConvertFrom(from, to))
{
meth = (r) => Convert.ChangeType(r, to);
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
// search for toWhatnot (very bad should be done last)
foreach (MethodInfo mi in @from.GetMethods(BindingFlagsInstance))
{
if (!mi.IsStatic)
{
var ps = mi.GetParameters();
if (ps.Length == 0)
{
if (!to.IsAssignableFrom(mi.ReturnType)) continue;
//Type pt = ps[0].ParameterType;
//if (pt.IsAssignableFrom(from))
{
MethodInfo info = mi;
meth = (r) => info.Invoke(r, ZERO_OBJECTS);
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
}
}
}
// search for to.Whatnot (very very bad should be done last)
if (pc != null)
{
meth = null;
int fieldCount = 0;
foreach (var f in to.GetFields(BindingFlagsInstance))
{
fieldCount++;
if (fieldCount > 1)
{
// too many fields
break;
}
FieldInfo info = f;
meth = (r) =>
{
var ret = pc.Invoke(null);
info.SetValue(ret, r);
return ret;
};
}
if (fieldCount == 1 && meth != null)
{
if (allMethods != null) allMethods.Add(meth);
else return meth;
}
}
return sysmeth;
}
public static void cliRegisterConvertor(Type p0)
{
cliRegisterConvertor(p0,true);
}
private static void cliRegisterConvertor(Type p0, bool addAll)
{
lock (ConvertorClasses)
{
if (ConvertorClasses.Contains(p0)) return;
ConvertorClasses.Insert(0,p0);
}
MethodInfo[] methods = p0.GetMethods(BindingFlagsJustStatic);
if (!addAll)
{
addAll = hadAttribute(p0, typeof(TypeConversionAttribute),false);
}
foreach (var m in methods)
{
if (!addAll)
{
if (!hadAttribute(m,typeof(TypeConversionAttribute), false)) continue;
}
registerConversion(m, null, null);
}
}
private static bool hadAttribute(MemberInfo p0, Type attribute, bool inherit)
{
object[] f = p0.GetCustomAttributes(attribute, inherit);
if (f == null || f.Length == 0) return false;
return true;
}
/// <summary>
/// This finds things like op_Implicit/op_Explicition to
/// </summary>
/// <param name="to"></param>
/// <param name="srch"></param>
/// <param name="from"></param>
/// <param name="allMethods"></param>
/// <param name="onlyConverionAttribute"></param>
/// <returns></returns>
private static OBJ_TO_OBJ SomeConversionStaticMethod(Type to, Type srch, Type from, ICollection<OBJ_TO_OBJ> allMethods, bool onlyConverionAttribute)
{
OBJ_TO_OBJ meth;
foreach (MethodInfo mi in srch.GetMethods(BindingFlagsJustStatic))
{
if (mi.IsStatic)
{
var ps = mi.GetParameters();
if (ps.Length == 1)
{
if (!to.IsAssignableFrom(mi.ReturnType)) continue;
if (onlyConverionAttribute)
{
if(!hadAttribute(mi,typeof(TypeConversionAttribute), true)) continue;
}
Type pt = ps[0].ParameterType;
if (pt.IsAssignableFrom(@from))
{
MethodInfo info = mi;
meth = (r) => info.Invoke(null, new object[] { r });
if (allMethods != null) allMethods.Add(meth); else return meth;
}
}
}
}
return null;
}
public static Object CastTerm0(PlTerm o, Type pt)
{
return CastTerm1(o, pt);
}
public static Object CastTerm1(PlTerm o, Type pt)
{
if (pt == typeof(PlTerm)) return o;
if (pt == typeof(string))
{
if (IsTaggedObject(o))
{
return "" + GetInstance(o);
}
return (string)o;
}
if (pt != null && pt.IsSubclassOf(typeof(Delegate)))
{
return cliNewDelegateTerm(pt, o, false);
}
if (pt == typeof(Type))
{
return GetType(o);
}
PlType plType = o.PlType;
switch (plType)
{
case PlType.PlUnknown:
{
return (string)o;
}
break;
case PlType.PlVariable:
{
return o;
}
break;
case PlType.PlInteger:
{
int i = 0;
if (0 != libpl.PL_get_integer(o.TermRef, ref i))
return i;
try
{
return (long)o;
}
catch (Exception)
{
}
try
{
return (ulong)o;
}
catch (Exception)
{
return ToBigInteger((string)o);
}
}
break;
case PlType.PlFloat:
{
try
{
return (double)o;
}
catch (Exception)
{
return ToBigDecimal((string)o);
}
}
break;
case PlType.PlNil:
{
return CoerceNil(pt);
}
case PlType.PlAtom:
case PlType.PlString:
{
if (plType == PlType.PlAtom && o.Name == "[]")
{
return CoerceNil(pt);
}
string s = (string)o;
if (pt == null) return s;
var constructor = pt.GetConstructor(ONE_STRING);
if (constructor != null)
{
return constructor.Invoke(new object[] { s });
}
foreach (var m in pt.GetMethods(BindingFlagsJustStatic))
{
ParameterInfo[] mGetParameters = m.GetParameters();
if (pt.IsAssignableFrom(m.ReturnType) && mGetParameters.Length == 1 &&
mGetParameters[0].ParameterType.IsAssignableFrom(typeof(string)))
{
Embedded.Debug("using " + m);
try
{
return m.Invoke(null, new object[] { s });
}
catch (Exception la)
{
Exception why = cliInnerException(la, -1);
var issue = "Cast failed converion " + why;
Embedded.Debug(issue);
continue;
}
}
} foreach (var m in pt.GetFields(BindingFlagsJustStatic))
{
if (pt.IsAssignableFrom(m.FieldType) && m.Name == s)
{
Embedded.Debug("using static field " + m);
return m.GetValue(null);
}
}
return s;
}
break;
case PlType.PlTerm:
case PlType.PlListPair:
{
lock (ToFromConvertLock)
{
var o1 = o[1];
return CastCompoundTerm(o.Name, o.Arity, o1, o, pt);
}
}
break;
default:
throw new ArgumentOutOfRangeException("plType=" + plType + " " + o.GetType() + " -> " + pt);
}
}
private static object CoerceNil( Type pt)
{
if (pt != null && pt.IsArray)
{
return Array.CreateInstance(pt.GetElementType(), 0);
}
return GetDefault(pt);
}
public static object GetDefault(Type type)
{
if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
public static Exception cliInnerException(Exception la, int depth)
{
Exception why = la.InnerException;
if (why == null) return la;
if (why != la)
{
if (depth < -0 || depth > 0)
{
depth--;
return cliInnerException(why, depth);
}
}
return why;
}
private static int ToVMNumber(object o, PlTerm term)
{
if (o is int)
return libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o));
if (PreserveObjectType)
{
return PlSucceedOrFail(UnifyTagged(o, term));
}
// signed types
if (o is short || o is sbyte)
return libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o));
if (o is long)
return libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o));
if (o is decimal || o is Single || o is float || o is double)
return libpl.PL_unify_float(term.TermRef, (double)Convert.ToDouble(o));
// unsigned types
if (o is ushort || o is byte)
return libpl.PL_unify_integer(term.TermRef, (int)Convert.ToInt32(o));
if (o is UInt32)
return libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o));
// potentually too big?!
if (o is ulong)
{
ulong u64 = (ulong)o;
if (u64 <= Int64.MaxValue)
{
return libpl.PL_unify_integer(term.TermRef, (long)Convert.ToInt64(o));
}
return PlSucceedOrFail(term.Unify(u64));
//return libpl.PL_unify_float(term.TermRef, (double)Convert.ToDouble(o));
}
if (o is IntPtr)
{
return libpl.PL_unify_intptr(term.TermRef, (IntPtr)o);
}
if (o is UIntPtr)
{
return libpl.PL_unify_intptr(term.TermRef, (IntPtr)o);
}
return -1;
}
/*
jpl_is_ref(@(Y)) :-
atom(Y), % presumably a (garbage-collectable) tag
Y \== void, % not a ref
Y \== false, % not a ref
Y \== true. % not a ref
*/
private static object CastCompoundTerm(string name, int arity, PlTerm arg1, PlTerm orig, Type pt)
{
if (pt != null)
{
object tagObj = findTaggedObject(pt, orig, arg1, orig[arity]);
if (tagObj != null && pt.IsInstanceOfType(tagObj)) return tagObj;
}
string key = name + "/" + arity;
lock (FunctorToLayout)
{
PrologTermLayout pltl;
if (FunctorToLayout.TryGetValue(key, out pltl))
{
Type type = pltl.ObjectType;
MemberInfo[] fis = pltl.FieldInfos;
MemberInfo toType = pltl.ToType;
if (toType != null)
{
return GetMemberValue(toType, CastTerm(arg1, argOneType(toType)));
}
return CreateInstance(type, fis, orig, 1);
}
}
lock (FunctorToRecomposer)
{
PrologTermRecomposer layout;
if (FunctorToRecomposer.TryGetValue(key, out layout))
{
Type type = layout.ToType;
uint newref = libpl.PL_new_term_ref();
PlTerm outto = new PlTerm(newref);
var ret = PlQuery.PlCall(layout.module, layout.r2obj, new PlTermV(orig, outto));
if (ret)
{
object o = CastTerm(outto, type);
if (!pt.IsInstanceOfType(o))
{
Embedded.Warn(type + " (" + o + ") is not " + pt);
}
return o;
}
}
}
if (key == "[]/0")
{
if (pt != null)
{
if (pt.IsArray)
{
return Array.CreateInstance(pt.GetElementType(), 0);
}
return MakeDefaultInstance(pt);
}
Embedded.Debug("Not sure what to convert `[]` too");
return null;
}
if (key == "static/1")
{
return null;
}
if (key == "delegate/1")
{
return CastTerm0(arg1, pt);
}
if (key == "delegate/2")
{
return cliNewDelegateTerm(pt, orig, false);
}
if (key == "{}/1")
{
return arg1;
}
if (pt == typeof(object))
{
pt = null;
}
//{T}
//@(_Tag)
if (key == "@/1" && arg1.IsAtom)
{
name = arg1.Name;
switch (name)
{
case "true":
{
return true;
}
case "false":
{
return false;
}
case "null":
{
if (pt != null && pt.IsValueType)
{
return MakeDefaultInstance(pt);
}
return null;
}
case "void":
{
#if USE_IKVM
if (pt == typeof(void)) return JPL.JVOID;
#endif
return null;
}
default:
{
{
object o = tag_to_object(name);
if (o == null)
{
Embedded.Warn("Null from tag " + name);
}
return o;
#if plvar_pins
lock (ToFromConvertLock) lock (atomToPlRef)
{
PlRef oldValue;
if (!atomToPlRef.TryGetValue(name, out oldValue))
{
//Warn("no value for tag=" + name);
if (pt != null && pt.IsInstanceOfType(o))
{
return o;
}
return o;
}
var v = oldValue.Value;
if (pt != null && pt.IsInstanceOfType(v))
{
return v;
}
return v;
}
#endif
}
}
}
}
#if plvar_pins
if (name == "$cli_object")
{
lock (ToFromConvertLock)
{
lock (termToObjectPins)
{
PlRef oldValue;
Int64 ohandle = (long)arg1;
if (!termToObjectPins.TryGetValue(ohandle, out oldValue))
{
Warn("no value for ohandle=" + ohandle);
}
return oldValue.Value;
}
}
}
#endif
if (key == "enum/2")
{
Type type = GetType(arg1);
PlTerm arg2 = orig.Arg(1);
object value = Enum.Parse(type, arg2.Name, true);
if (value == null) Embedded.Warn("cant parse enum: {0} for type {1}", arg2, type);
return value;
}
if (key == "array/2")
{
Type type = GetType(arg1);
return CreateArrayOfTypeRankOneFilled(orig.Arg(1), type.MakeArrayType());
}
if (key == "array/3")
{
Type type = GetType(arg1);
var ar = CreateArrayOfType(ToTermArray(orig.Arg(1)), type);
FillArray(ToTermArray(orig.Arg(2)), type.GetElementType(), ar);
return ar;
}
if (name == "values")
{
Embedded.Warn("Values array");
}
if (name == "struct" || name == "event" || name == "object")
{
Type type = GetType(arg1);
MemberInfo[] fis = GetStructFormat(type);
return CreateInstance(type, fis, orig, 2);
}
if (orig.IsList)
{
if (arg1.IsInteger || arg1.IsAtom)
{
Embedded.Debug("maybe this is a string {0}", orig);
}
if (pt == null)
{
var o1 = GetInstance(arg1);
if (false && o1 != null && IsTaggedObject(arg1) && arg1.IsCompound && !o1.GetType().IsPrimitive)
{
Embedded.Warn(" send a list into cliGet0 ", orig);
bool found;
var res = cliGet0(arg1, orig.Arg(1), o1.GetType(), out found,
BindingFlagsALL3 | BindingFlagsALL);
if (found) return res;
}
Embedded.Debug("Return as array of object[]?", orig);
var o = CreateArrayNarrowest(ToObjectArray(ToTermArray(orig)));
return o;
}
else
{
if (pt.IsArray)
{
return CreateArrayOfTypeRankOneFilled(orig, pt);
}
if (!typeof(IEnumerable).IsAssignableFrom(pt))
{
Embedded.Warn("Return as collection?", orig);
}
return CreateCollectionOfType(orig, pt);
}
}
if (pt != null && pt.IsArray)
{
return CreateArrayOfTypeRankOneFilled(orig, pt);
}
Type t = ResolveType(name);
if (t == null)
{
if (pt != null)
{
object tagObj = findTaggedObject(pt, arg1, orig[arity]);
if (tagObj != null && pt.IsInstanceOfType(tagObj)) return tagObj;
}
else
{
object tagObj = findTaggedObject(pt, arg1, orig[arity]);
if (tagObj != null) return tagObj;
}
Embedded.WarnMissing(String.Format("Cant GetInstance from {0}", orig));
return orig;
}
if (pt == null || pt.IsAssignableFrom(t))
{
if (arity == 1)
{
return CastTerm(arg1, t);
}
foreach (var m in t.GetConstructors())
{
ParameterInfo[] mGetParameters = m.GetParameters();
if (mGetParameters.Length == arity)
{
Action postCallHook;
try
{
Embedded.WarnMissing("using contructor {0}", m);
var values = PlListToCastedArray(orig, mGetParameters, out postCallHook);
var retval = m.Invoke(values);
Dictionary<string, object> threadLocals = cliTLMem();
CommitPostCall(postCallHook);
return retval;
}
catch (Exception)
{
}
}
}
}
Embedded.Debug("Get Instance fallthru");
MemberInfo[] ofs = GetStructFormat(t);
return CreateInstance(t, ofs, orig, 1);
}
private static object findTaggedObject(Type pt, params PlTerm[] args)
{
foreach (var arg1 in args)
{
if (IsTaggedObject(arg1))
{
object tagObj = tag_to_object(arg1[1].Name);
if (tagObj != null)
{
if (pt == null || pt.IsInstanceOfType(tagObj)) return tagObj;
}
}
}
return null;
}
[ThreadStatic] private static Dictionary<string, object> threadLocaldict;
private static Dictionary<string, object> cliTLMem()
{
if (threadLocaldict==null) threadLocaldict = new Dictionary<string, object>();
return threadLocaldict;
}
}
public class TypeConversionAttribute : Attribute
{
}
[TypeConversion]
internal class PrologConvert //: OpenMetaverse.UUIDFactory
{
[TypeConversion]
static public Guid ToGuid(object from)
{
return new Guid("" + from);
}
[TypeConversion]
static public String ToStr(object from)
{
return "" + from;
}
[TypeConversion]
static public Type ToType(PlTerm typeSpec)
{
return PrologCLR.GetTypeThrowIfMissing(typeSpec);
}
[TypeConversion]
unsafe static public string Convert(char* from)
{
return new string(from);
}
[TypeConversion]
unsafe static public char* Convert(Pointer from)
{
void* vp = Pointer.Unbox(from);
char* cp;
cp = (char*) vp;
return cp;
}
[TypeConversion]
public static unsafe char* Convert(String from)
{
fixed (char* p = from)
return p;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using NUnit.Framework;
using Microsoft.Build;
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Framework;
using Microsoft.Build.UnitTests;
namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility
{
/// <summary>
/// Fixture Class for the v9 OM Public Interface Compatibility Tests. Import Class.
/// Also see Toolset tests in the Project test class.
/// </summary>
[TestFixture]
public class InvalidProjectfileException_Tests
{
/// <summary>
/// Ctor test, default construction is supported.
/// </summary>
[Test]
public void CtorDefault()
{
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException();
}
/// <summary>
/// Ctor Test, with message
/// </summary>
[Test]
public void CtorMessageArity1()
{
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException("Message");
Assertion.AssertEquals("Message", invalidProjectFileException.Message);
Assertion.AssertEquals(0, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(0, invalidProjectFileException.ColumnNumber);
}
///<summary>
/// Ctor Test, with null message
/// </summary>
[Test]
public void CtorMessageArity1_null()
{
string nullString = null; // typed null as to hit correct ctor overloaded.
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException(nullString);
InvalidProjectFileException invalidProjectFileException2 = new InvalidProjectFileException(nullString, new Exception("MessageInner"));
}
/// <summary>
/// Ctor Test, with an empty string message
/// </summary>
[Test]
public void CtorMessageArity1_empty()
{
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException(String.Empty);
InvalidProjectFileException invalidProjectFileException2 = new InvalidProjectFileException(String.Empty, new Exception("MessageInner"));
}
/// <summary>
/// Ctor Test, with message and inner exception
/// </summary>
[Test]
public void Ctor_Arity2InnerException()
{
InvalidProjectFileException invalidProjectFileException = new InvalidProjectFileException("Message", new Exception("MessageInner"));
Assertion.AssertEquals("Message", invalidProjectFileException.Message);
Assertion.AssertEquals("MessageInner", invalidProjectFileException.InnerException.Message);
Assertion.AssertEquals(0, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(0, invalidProjectFileException.ColumnNumber);
}
/// <summary>
/// Ctor Test, Construct with a mock project element. There is no way to test this on concrete project as the xml tree is internalised.
/// </summary>
[Test]
public void CtorArity4()
{
string message = "Message";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(new XmlDocument().CreateElement("name"), message, "errorSubCategory", "errorCode", "HelpKeyword");
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ProjectFile);
// preserve a bug in Orcas SP1: if projectFile is empty but non-null, extra spaces get added to the message.
Assertion.AssertEquals(message + " ", invalidProjectFileException.Message);
Assertion.AssertEquals("errorSubCategory", invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals("errorCode", invalidProjectFileException.ErrorCode);
Assertion.AssertEquals("HelpKeyword", invalidProjectFileException.HelpKeyword);
Assertion.AssertEquals(0, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(0, invalidProjectFileException.ColumnNumber);
}
/// <summary>
/// Ctor Test, Construct with a mock project element and a Null message string
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void CtorArity4_NullMessageString()
{
string message = null;
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(new XmlDocument().CreateElement("name"), message, "subcategory", "ErrorCode", "HelpKeyword");
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ProjectFile);
Assertion.AssertEquals(message, invalidProjectFileException.Message);
Assertion.AssertNull(invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals("ErrorCode", invalidProjectFileException.ErrorCode);
Assertion.AssertEquals("HelpKeyword", invalidProjectFileException.HelpKeyword);
Assertion.AssertEquals(0, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(0, invalidProjectFileException.ColumnNumber);
}
/// <summary>
/// Ctor Test
/// </summary>
[Test]
[ExpectedException(typeof(ArgumentException))]
public void CtorArity4_EmptyMessageString()
{
string message = String.Empty;
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(new XmlDocument().CreateElement("Name"), message, String.Empty, String.Empty, String.Empty);
}
/// <summary>
/// Ctor Testt
/// </summary>
[Test]
public void CtorArity4_EmptyStringOtherParams()
{
string message = "Message";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(new XmlDocument().CreateElement("Name"), message, String.Empty, String.Empty, String.Empty);
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ProjectFile);
// preserve a bug in Orcas SP1: if projectFile is empty but non-null, extra spaces get added to the message.
Assertion.AssertEquals(message + " ", invalidProjectFileException.Message);
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ErrorCode);
Assertion.AssertEquals(String.Empty, invalidProjectFileException.HelpKeyword);
Assertion.AssertEquals(0, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(0, invalidProjectFileException.ColumnNumber);
}
/// <summary>
/// Ctor Test
/// </summary>
[Test]
public void CtorArity4_NullStringOtherParams()
{
string message = "Message";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(new XmlDocument().CreateElement("Name"), message, null, null, null);
Assertion.AssertEquals(String.Empty, invalidProjectFileException.ProjectFile);
// preserve a bug in Orcas SP1: if projectFile is empty but non-null, extra spaces get added to the message.
Assertion.AssertEquals(message + " ", invalidProjectFileException.Message);
Assertion.AssertEquals(null, invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals(null, invalidProjectFileException.ErrorCode);
Assertion.AssertEquals(null, invalidProjectFileException.HelpKeyword);
}
/// <summary>
/// Ctor Test
/// </summary>
[Test]
public void Ctor_Arity9PositveInts()
{
string message = "Message";
string projectFile = @"c:\ProjectFile";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(projectFile, 1, 10, 11, 12, message, "errorSubCategory", "errorCode", "HelpKeyword");
Assertion.AssertEquals(message + " " + projectFile, invalidProjectFileException.Message);
Assertion.AssertEquals("errorSubCategory", invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals("errorCode", invalidProjectFileException.ErrorCode);
Assertion.AssertEquals("HelpKeyword", invalidProjectFileException.HelpKeyword);
Assertion.AssertEquals(1, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(10, invalidProjectFileException.ColumnNumber);
Assertion.AssertEquals(11, invalidProjectFileException.EndLineNumber);
Assertion.AssertEquals(12, invalidProjectFileException.EndColumnNumber);
}
/// <summary>
/// Ctor Test, this enforces lack of bounds checking and the lack of range checking (end can come before start)
/// on the line and column number params.
/// </summary>
[Test]
public void CtorArity9NegativeInts()
{
string message = "Message";
string projectFile = @"c:\ProjectFile";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(projectFile, -1, -10, -11, -12, message, "errorSubCategory", "errorCode", "HelpKeyword");
Assertion.AssertEquals(message + " " + projectFile, invalidProjectFileException.Message);
Assertion.AssertEquals("errorSubCategory", invalidProjectFileException.ErrorSubcategory);
Assertion.AssertEquals("errorCode", invalidProjectFileException.ErrorCode);
Assertion.AssertEquals("HelpKeyword", invalidProjectFileException.HelpKeyword);
Assertion.AssertEquals(-1, invalidProjectFileException.LineNumber);
Assertion.AssertEquals(-10, invalidProjectFileException.ColumnNumber);
Assertion.AssertEquals(-11, invalidProjectFileException.EndLineNumber);
Assertion.AssertEquals(-12, invalidProjectFileException.EndColumnNumber);
Assertion.AssertEquals(projectFile, invalidProjectFileException.ProjectFile);
}
/// <summary>
/// BaseMessage, get and set
/// </summary>
[Test]
public void BaseMessage()
{
string message = "Message";
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException("ProjectFile", 0, 0, 0, 0, message, "errorSubCategory", "errorCode", "HelpKeyword");
Assertion.AssertEquals(message, invalidProjectFileException.BaseMessage);
}
/// <summary>
/// XML Serialization Test, not supported, throws invalid operation Exception.
/// </summary>
[Test]
[ExpectedException(typeof(InvalidOperationException))]
public void SerializationXML()
{
InvalidProjectFileException toolSetException = new InvalidProjectFileException("Message", new Exception("innerException"));
MemoryStream memoryStream = null;
try
{
memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(InvalidProjectFileException));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, toolSetException);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
}
finally
{
memoryStream.Close();
}
}
/// <summary>
/// Binary Serialization Test, serialize the exception out and back in from a stream. This uses the protected constructor
/// </summary>
[Test]
public void SerializationBinary()
{
string message = "Message";
string projectFile = @"c:\ProjectFile";
MemoryStream memoryStream = null;
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException(projectFile, 1, 2, 3, 4, message, "errorSubCategory", "errorCode", "HelpKeyword");
try
{
memoryStream = new MemoryStream();
IFormatter binaryForamtter = new BinaryFormatter();
binaryForamtter.Serialize(memoryStream, invalidProjectFileException);
memoryStream.Position = 0; // reset pointer into stream for read
Object returnObj = binaryForamtter.Deserialize(memoryStream);
Assertion.Assert(returnObj is InvalidProjectFileException);
InvalidProjectFileException outException = ((InvalidProjectFileException)returnObj);
Assertion.AssertEquals(message + " " + projectFile, outException.Message);
Assertion.AssertEquals("errorSubCategory", outException.ErrorSubcategory);
Assertion.AssertEquals("errorCode", outException.ErrorCode);
Assertion.AssertEquals("HelpKeyword", outException.HelpKeyword);
Assertion.AssertEquals(1, outException.LineNumber);
Assertion.AssertEquals(2, outException.ColumnNumber);
Assertion.AssertEquals(3, outException.EndLineNumber);
Assertion.AssertEquals(4, outException.EndColumnNumber);
Assertion.AssertEquals(projectFile, outException.ProjectFile);
}
finally
{
memoryStream.Close();
}
}
/// <summary>
/// Binary Serialization Test, serialize the exception out and back in from a stream with an InnerException. This uses the protected constructor
/// </summary>
[Test]
public void SerializationBinaryInnerException()
{
MemoryStream memoryStream = null;
InvalidProjectFileException invalidProjectFileException =
new InvalidProjectFileException("Message", new Exception("innerException"));
try
{
memoryStream = new MemoryStream();
IFormatter binaryForamtter = new BinaryFormatter();
binaryForamtter.Serialize(memoryStream, invalidProjectFileException);
memoryStream.Position = 0; // reset pointer into stream for read
Object returnObj = binaryForamtter.Deserialize(memoryStream);
Assertion.Assert(returnObj is InvalidProjectFileException);
InvalidProjectFileException outException = ((InvalidProjectFileException)returnObj);
Assertion.AssertEquals("Message", outException.Message);
Assertion.AssertEquals("innerException", outException.InnerException.Message);
}
finally
{
memoryStream.Close();
}
}
}
}
| |
//
// This file is part of the game Voxalia, created by FreneticXYZ.
// This code is Copyright (C) 2016 FreneticXYZ under the terms of the MIT license.
// See README.md or LICENSE.txt for contents of the MIT license.
// If these are not available, see https://opensource.org/licenses/MIT
//
using System;
using System.Collections.Generic;
using Voxalia.Shared;
using Voxalia.ServerGame.NetworkSystem.PacketsOut;
using Voxalia.ServerGame.WorldSystem;
using Voxalia.Shared.Collision;
using Voxalia.ServerGame.NetworkSystem;
using LiteDB;
namespace Voxalia.ServerGame.EntitySystem
{
public class CollisionEventArgs : EventArgs
{
public CollisionEventArgs(CollisionResult cr)
{
Info = cr;
}
public CollisionResult Info;
}
public abstract class PrimitiveEntity: Entity
{
public Location Gravity = Location.Zero;
public HashSet<long> NoCollide = new HashSet<long>();
public abstract string GetModel();
public override long GetRAMUsage()
{
return base.GetRAMUsage() + 50 + NoCollide.Count * 16;
}
public PrimitiveEntity(Region tregion)
: base(tregion, true)
{
}
public const int PrimitiveNetDataLength = 24 + 24 + 16 + 24 + 24 + 4;
public byte[] GetPrimitiveNetData()
{
byte[] Data = new byte[PrimitiveNetDataLength];
GetPosition().ToDoubleBytes().CopyTo(Data, 0);
GetVelocity().ToDoubleBytes().CopyTo(Data, 24);
Utilities.QuaternionToBytes(Angles).CopyTo(Data, 24 + 24);
Scale.ToDoubleBytes().CopyTo(Data, 24 + 24 + 16);
Gravity.ToDoubleBytes().CopyTo(Data, 24 + 24 + 16 + 24);
Utilities.IntToBytes(TheServer.Networking.Strings.IndexForString(GetModel())).CopyTo(Data, 24 + 24 + 16 + 24 + 24);
return Data;
}
public override void PotentialActivate()
{
}
public bool network = true;
public bool FilterHandle(BEPUphysics.BroadPhaseEntries.BroadPhaseEntry entry)
{
if (entry is BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)
{
long eid = ((PhysicsEntity)((BEPUphysics.BroadPhaseEntries.MobileCollidables.EntityCollidable)entry).Entity.Tag).EID;
if (NoCollide.Contains(eid))
{
return false;
}
}
return TheRegion.Collision.ShouldCollide(entry);
}
public double netdeltat = 0;
public override void Tick()
{
if (TheRegion.IsVisible(GetPosition()))
{
bool sme = false;
SetVelocity(GetVelocity() * 0.99f + Gravity * TheRegion.Delta);
if (GetVelocity().LengthSquared() > 0)
{
CollisionResult cr = TheRegion.Collision.CuboidLineTrace(Scale, GetPosition(), GetPosition() + GetVelocity() * TheRegion.Delta, FilterHandle);
Location vel = GetVelocity();
if (cr.Hit && Collide != null)
{
Collide(this, new CollisionEventArgs(cr));
}
if (!IsSpawned || Removed)
{
return;
}
if (vel == GetVelocity())
{
SetVelocity((cr.Position - GetPosition()) / TheRegion.Delta);
}
SetPosition(cr.Position);
// TODO: Timer
if (network)
{
sme = true;
}
netdeltat = 2;
}
else
{
netdeltat += TheRegion.Delta;
if (netdeltat > 2.0)
{
netdeltat -= 2.0;
sme = true;
}
}
Location pos = GetPosition();
PrimitiveEntityUpdatePacketOut primupd = sme ? new PrimitiveEntityUpdatePacketOut(this) : null;
foreach (PlayerEntity player in TheRegion.Players)
{
bool shouldseec = player.ShouldSeePosition(pos);
bool shouldseel = player.ShouldSeePositionPreviously(lPos);
if (shouldseec && !shouldseel)
{
player.Network.SendPacket(GetSpawnPacket());
}
if (shouldseel && !shouldseec)
{
player.Network.SendPacket(new DespawnEntityPacketOut(EID));
}
if (sme && shouldseec)
{
player.Network.SendPacket(primupd);
}
}
}
lPos = GetPosition();
Vector3i cpos = TheRegion.ChunkLocFor(lPos);
if (CanSave && !TheRegion.LoadedChunks.ContainsKey(cpos))
{
TheRegion.LoadChunk(cpos);
}
}
public Location lPos = Location.NaN;
public EventHandler<CollisionEventArgs> Collide;
public virtual void Spawn()
{
NoCollide.Add(EID);
}
public virtual void Destroy()
{
NoCollide.Remove(EID);
}
public Location Position;
public Location Velocity;
public Location Scale;
public BEPUutilities.Quaternion Angles;
public override Location GetPosition()
{
return Position;
}
public override void SetPosition(Location pos)
{
Position = pos;
}
public Location GetVelocity()
{
return Velocity;
}
public virtual void SetVelocity(Location vel)
{
Velocity = vel;
}
public override BEPUutilities.Quaternion GetOrientation()
{
return Angles;
}
public override void SetOrientation(BEPUutilities.Quaternion quat)
{
Angles = quat;
}
public void ApplyPrimitiveSaveData(BsonDocument doc)
{
Position = Location.FromDoubleBytes(doc["prim_pos"].AsBinary, 0);
Velocity = Location.FromDoubleBytes(doc["prim_vel"].AsBinary, 0);
Scale = Location.FromDoubleBytes(doc["prim_scale"].AsBinary, 0);
Gravity = Location.FromDoubleBytes(doc["prim_grav"].AsBinary, 0);
double x = doc["prim_ang_x"].AsDouble;
double y = doc["prim_ang_y"].AsDouble;
double z = doc["prim_ang_z"].AsDouble;
double w = doc["prim_ang_w"].AsDouble;
SetOrientation(new BEPUutilities.Quaternion(x, y, z, w));
foreach (BsonValue bsv in doc["prim_noco"].AsArray)
{
NoCollide.Add(bsv.AsInt64);
}
}
public override BsonDocument GetSaveData()
{
BsonDocument doc = new BsonDocument();
doc["prim_pos"] = Position.ToDoubleBytes();
doc["prim_vel"] = Velocity.ToDoubleBytes();
doc["prim_scale"] = Scale.ToDoubleBytes();
doc["prim_grav"] = Gravity.ToDoubleBytes();
BEPUutilities.Quaternion quat = GetOrientation();
doc["prim_ang_x"] = (double)quat.X;
doc["prim_ang_y"] = (double)quat.Y;
doc["prim_ang_z"] = (double)quat.Z;
doc["prim_ang_w"] = (double)quat.W;
BsonArray b = new BsonArray();
foreach (long l in NoCollide)
{
b.Add(l);
}
doc["prim_noco"] = b;
return doc;
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Algo.Algo
File: BasketMessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Algo
{
using System;
using System.Collections.Generic;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Serialization;
using MoreLinq;
using StockSharp.Algo.Storages;
using StockSharp.Logging;
using StockSharp.Messages;
using StockSharp.Localization;
using SubscriptionInfo = System.Tuple<Messages.SecurityId, Messages.MarketDataTypes, object, System.DateTimeOffset?, System.DateTimeOffset?, long?, int?>;
/// <summary>
/// The interface describing the list of adapters to trading systems with which the aggregator operates.
/// </summary>
public interface IInnerAdapterList : ISynchronizedCollection<IMessageAdapter>, INotifyList<IMessageAdapter>
{
/// <summary>
/// Internal adapters sorted by operation speed.
/// </summary>
IEnumerable<IMessageAdapter> SortedAdapters { get; }
/// <summary>
/// The indexer through which speed priorities (the smaller the value, then adapter is faster) for internal adapters are set.
/// </summary>
/// <param name="adapter">The internal adapter.</param>
/// <returns>The adapter priority. If the -1 value is set the adapter is considered to be off.</returns>
int this[IMessageAdapter adapter] { get; set; }
}
/// <summary>
/// Adapter-aggregator that allows simultaneously to operate multiple adapters connected to different trading systems.
/// </summary>
public class BasketMessageAdapter : MessageAdapter, IMessageAdapterProvider
{
private sealed class InnerAdapterList : CachedSynchronizedList<IMessageAdapter>, IInnerAdapterList
{
private readonly Dictionary<IMessageAdapter, int> _enables = new Dictionary<IMessageAdapter, int>();
public IEnumerable<IMessageAdapter> SortedAdapters
{
get { return Cache.Where(t => this[t] != -1).OrderBy(t => this[t]); }
}
protected override bool OnAdding(IMessageAdapter item)
{
_enables.Add(item, 0);
return base.OnAdding(item);
}
protected override bool OnInserting(int index, IMessageAdapter item)
{
_enables.Add(item, 0);
return base.OnInserting(index, item);
}
protected override bool OnRemoving(IMessageAdapter item)
{
_enables.Remove(item);
return base.OnRemoving(item);
}
protected override bool OnClearing()
{
_enables.Clear();
return base.OnClearing();
}
public int this[IMessageAdapter adapter]
{
get
{
lock (SyncRoot)
return _enables.TryGetValue2(adapter) ?? -1;
}
set
{
if (value < -1)
throw new ArgumentOutOfRangeException();
lock (SyncRoot)
{
if (!Contains(adapter))
Add(adapter);
_enables[adapter] = value;
//_portfolioTraders.Clear();
}
}
}
}
private enum SubscriptionStates
{
Subscribed,
Subscribing,
Unsubscribing,
}
private readonly SynchronizedDictionary<SubscriptionInfo, SubscriptionStates> _subscriptionStates = new SynchronizedDictionary<SubscriptionInfo, SubscriptionStates>();
private readonly SynchronizedPairSet<SubscriptionInfo, IEnumerator<IMessageAdapter>> _subscriptionQueue = new SynchronizedPairSet<SubscriptionInfo, IEnumerator<IMessageAdapter>>();
private readonly SynchronizedDictionary<long, SubscriptionInfo> _subscriptionKeys = new SynchronizedDictionary<long, SubscriptionInfo>();
private readonly SynchronizedDictionary<SubscriptionInfo, IMessageAdapter> _subscriptions = new SynchronizedDictionary<SubscriptionInfo, IMessageAdapter>();
//private readonly SynchronizedDictionary<IMessageAdapter, RefPair<bool, Exception>> _adapterStates = new SynchronizedDictionary<IMessageAdapter, RefPair<bool, Exception>>();
private readonly SynchronizedDictionary<IMessageAdapter, HeartbeatMessageAdapter> _hearbeatAdapters = new SynchronizedDictionary<IMessageAdapter, HeartbeatMessageAdapter>();
private readonly SynchronizedDictionary<MessageTypes, CachedSynchronizedList<IMessageAdapter>> _messageTypeAdapters = new SynchronizedDictionary<MessageTypes, CachedSynchronizedList<IMessageAdapter>>();
private readonly CachedSynchronizedSet<HeartbeatMessageAdapter> _connectedAdapters = new CachedSynchronizedSet<HeartbeatMessageAdapter>();
private bool _isFirstConnect;
private readonly InnerAdapterList _innerAdapters;
/// <summary>
/// Adapters with which the aggregator operates.
/// </summary>
public IInnerAdapterList InnerAdapters => _innerAdapters;
/// <summary>
/// Portfolios which are used to send transactions.
/// </summary>
public IDictionary<string, IMessageAdapter> Portfolios { get; }
/// <summary>
/// Security native identifier storage.
/// </summary>
public INativeIdStorage NativeIdStorage { get; set; }
/// <summary>
/// Extended info <see cref="Message.ExtensionInfo"/> storage.
/// </summary>
public IExtendedInfoStorage ExtendedInfoStorage { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="BasketMessageAdapter"/>.
/// </summary>
/// <param name="transactionIdGenerator">Transaction id generator.</param>
public BasketMessageAdapter(IdGenerator transactionIdGenerator)
: base(transactionIdGenerator)
{
_innerAdapters = new InnerAdapterList();
Portfolios = new SynchronizedDictionary<string, IMessageAdapter>(StringComparer.InvariantCultureIgnoreCase);
}
/// <summary>
/// Supported by adapter message types.
/// </summary>
public override MessageTypes[] SupportedMessages
{
get { return GetSortedAdapters().SelectMany(a => a.SupportedMessages).Distinct().ToArray(); }
}
/// <summary>
/// <see cref="PortfolioLookupMessage"/> required to get portfolios and positions.
/// </summary>
public override bool PortfolioLookupRequired
{
get { return GetSortedAdapters().Any(a => a.PortfolioLookupRequired); }
}
/// <summary>
/// <see cref="OrderStatusMessage"/> required to get orders and ow trades.
/// </summary>
public override bool OrderStatusRequired
{
get { return GetSortedAdapters().Any(a => a.OrderStatusRequired); }
}
/// <summary>
/// <see cref="SecurityLookupMessage"/> required to get securities.
/// </summary>
public override bool SecurityLookupRequired
{
get { return GetSortedAdapters().Any(a => a.SecurityLookupRequired); }
}
/// <summary>
/// Gets a value indicating whether the connector supports position lookup.
/// </summary>
protected override bool IsSupportNativePortfolioLookup => true;
/// <summary>
/// Gets a value indicating whether the connector supports security lookup.
/// </summary>
protected override bool IsSupportNativeSecurityLookup => true;
/// <summary>
/// Restore subscription on reconnect.
/// </summary>
public bool IsRestorSubscriptioneOnReconnect { get; set; }
/// <summary>
/// Create condition for order type <see cref="OrderTypes.Conditional"/>, that supports the adapter.
/// </summary>
/// <returns>Order condition. If the connection does not support the order type <see cref="OrderTypes.Conditional"/>, it will be returned <see langword="null" />.</returns>
public override OrderCondition CreateOrderCondition()
{
throw new NotSupportedException();
}
/// <summary>
/// Check the connection is alive. Uses only for connected states.
/// </summary>
/// <returns><see langword="true" />, is the connection still alive, <see langword="false" />, if the connection was rejected.</returns>
public override bool IsConnectionAlive()
{
throw new NotSupportedException();
}
private void ProcessReset(Message message)
{
_hearbeatAdapters.Values.ForEach(a =>
{
a.SendInMessage(message);
a.Dispose();
});
_connectedAdapters.Clear();
_messageTypeAdapters.Clear();
_hearbeatAdapters.Clear();
_subscriptionQueue.Clear();
_subscriptions.Clear();
_subscriptionKeys.Clear();
_subscriptionStates.Clear();
}
private IMessageAdapter CreateWrappers(IMessageAdapter adapter)
{
if (adapter.IsNativeIdentifiers)
{
adapter = NativeIdStorage != null
? new SecurityNativeIdMessageAdapter(adapter, NativeIdStorage)
: new SecurityNativeIdMessageAdapter(adapter);
}
if (ExtendedInfoStorage != null && !adapter.SecurityExtendedFields.IsEmpty())
{
adapter = new ExtendedInfoStorageMessageAdapter(adapter, ExtendedInfoStorage.Get(adapter.StorageName, adapter.SecurityExtendedFields));
}
return new SubscriptionMessageAdapter(adapter) { IsRestoreOnReconnect = IsRestorSubscriptioneOnReconnect };
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
protected override void OnSendInMessage(Message message)
{
if (message.IsBack)
{
var adapter = message.Adapter;
if (adapter == null)
throw new InvalidOperationException();
adapter.SendInMessage(message);
return;
}
switch (message.Type)
{
case MessageTypes.Reset:
ProcessReset(message);
break;
case MessageTypes.Connect:
{
if (_isFirstConnect)
_isFirstConnect = false;
else
ProcessReset(new ResetMessage());
_hearbeatAdapters.AddRange(GetSortedAdapters().Select(CreateWrappers).ToDictionary(a => a, a =>
{
var hearbeatAdapter = new HeartbeatMessageAdapter(a);
((IMessageAdapter)hearbeatAdapter).Parent = this;
hearbeatAdapter.NewOutMessage += m => OnInnerAdapterNewOutMessage(a, m);
return hearbeatAdapter;
}));
if (_hearbeatAdapters.Count == 0)
throw new InvalidOperationException(LocalizedStrings.Str3650);
_hearbeatAdapters.Values.ForEach(a => a.SendInMessage(message));
break;
}
case MessageTypes.Disconnect:
{
_connectedAdapters.Cache.ForEach(a => a.SendInMessage(message));
break;
}
case MessageTypes.Portfolio:
{
var pfMsg = (PortfolioMessage)message;
ProcessPortfolioMessage(pfMsg.PortfolioName, pfMsg);
break;
}
case MessageTypes.OrderRegister:
case MessageTypes.OrderReplace:
case MessageTypes.OrderCancel:
case MessageTypes.OrderGroupCancel:
{
var ordMsg = (OrderMessage)message;
ProcessAdapterMessage(ordMsg.PortfolioName, ordMsg);
break;
}
case MessageTypes.OrderPairReplace:
{
var ordMsg = (OrderPairReplaceMessage)message;
ProcessAdapterMessage(ordMsg.Message1.PortfolioName, ordMsg);
break;
}
case MessageTypes.MarketData:
{
IMessageAdapter[] adapters = null;
if (message.Adapter != null)
{
var wrapper = _hearbeatAdapters.Values.FirstOrDefault(w => GetUnderlyingAdapter(w) == message.Adapter);
if (wrapper != null)
adapters = new IMessageAdapter[] {wrapper};
}
if (adapters == null)
adapters = _messageTypeAdapters.TryGetValue(message.Type)?.Cache;
if (adapters == null)
throw new InvalidOperationException(LocalizedStrings.Str629Params.Put(message.Type));
var mdMsg = (MarketDataMessage)message;
switch (mdMsg.DataType)
{
case MarketDataTypes.News:
adapters.ForEach(a => a.SendInMessage(mdMsg));
break;
default:
{
var key = CreateKey(mdMsg);
var state = _subscriptionStates.TryGetValue2(key);
if (mdMsg.IsSubscribe)
{
if (state != null)
{
RaiseMarketDataMessage(null, mdMsg.OriginalTransactionId, new InvalidOperationException(state.Value.ToString()), true);
break;
}
else
_subscriptionStates.Add(key, SubscriptionStates.Subscribing);
}
else
{
var canProcess = false;
switch (state)
{
case SubscriptionStates.Subscribed:
canProcess = true;
_subscriptionStates[key] = SubscriptionStates.Unsubscribing;
break;
case SubscriptionStates.Subscribing:
case SubscriptionStates.Unsubscribing:
RaiseMarketDataMessage(null, mdMsg.OriginalTransactionId, new InvalidOperationException(state.Value.ToString()), false);
break;
case null:
RaiseMarketDataMessage(null, mdMsg.OriginalTransactionId, null, false);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (!canProcess)
break;
}
if (mdMsg.TransactionId != 0)
_subscriptionKeys.Add(mdMsg.TransactionId, key);
if (mdMsg.IsSubscribe)
{
//if (_subscriptionQueue.ContainsKey(key))
// return;
var enumerator = adapters.Cast<IMessageAdapter>().GetEnumerator();
_subscriptionQueue.Add(key, enumerator);
ProcessSubscriptionAction(enumerator, mdMsg, mdMsg.TransactionId);
}
else
{
var adapter = _subscriptions.TryGetValue(key);
if (adapter != null)
{
_subscriptions.Remove(key);
adapter.SendInMessage(message);
}
}
break;
}
}
break;
}
case MessageTypes.ChangePassword:
{
var adapter = GetSortedAdapters().FirstOrDefault(a => a.SupportedMessages.Contains(MessageTypes.ChangePassword));
if (adapter == null)
throw new InvalidOperationException(LocalizedStrings.Str629Params.Put(message.Type));
adapter.SendInMessage(message);
break;
}
default:
{
if (message.Adapter != null)
{
message.Adapter.SendInMessage(message);
break;
}
var adapters = _messageTypeAdapters.TryGetValue(message.Type)?.Cache;
if (adapters == null)
throw new InvalidOperationException(LocalizedStrings.Str629Params.Put(message.Type));
adapters.ForEach(a => a.SendInMessage(message));
break;
}
}
}
private void ProcessAdapterMessage(string portfolioName, Message message)
{
var adapter = message.Adapter;
if (adapter == null)
ProcessPortfolioMessage(portfolioName, message);
else
adapter.SendInMessage(message);
}
private void ProcessPortfolioMessage(string portfolioName, Message message)
{
var adapter = portfolioName.IsEmpty() ? null : Portfolios.TryGetValue(portfolioName);
if (adapter == null)
{
var adapters = _messageTypeAdapters.TryGetValue(message.Type)?.Cache;
if (adapters == null || adapters.Length != 1)
throw new InvalidOperationException(LocalizedStrings.Str623Params.Put(portfolioName));
adapter = adapters.First();
}
else
adapter = _hearbeatAdapters[adapter];
adapter.SendInMessage(message);
}
/// <summary>
/// The embedded adapter event <see cref="IMessageChannel.NewOutMessage"/> handler.
/// </summary>
/// <param name="innerAdapter">The embedded adapter.</param>
/// <param name="message">Message.</param>
protected virtual void OnInnerAdapterNewOutMessage(IMessageAdapter innerAdapter, Message message)
{
if (!message.IsBack)
{
if (message.Adapter == null)
message.Adapter = innerAdapter;
switch (message.Type)
{
case MessageTypes.Connect:
ProcessConnectMessage(innerAdapter, (ConnectMessage)message);
return;
case MessageTypes.Disconnect:
ProcessDisconnectMessage(innerAdapter, (DisconnectMessage)message);
return;
case MessageTypes.MarketData:
ProcessMarketDataMessage(innerAdapter, (MarketDataMessage)message);
return;
}
}
SendOutMessage(message);
}
private static IMessageAdapter GetUnderlyingAdapter(IMessageAdapter adapter)
{
var wrapper = adapter as IMessageAdapterWrapper;
return wrapper != null ? GetUnderlyingAdapter(wrapper.InnerAdapter) : adapter;
}
private void ProcessConnectMessage(IMessageAdapter innerAdapter, ConnectMessage message)
{
var underlyingAdapter = GetUnderlyingAdapter(innerAdapter);
if (message.Error != null)
this.AddErrorLog(LocalizedStrings.Str625Params, underlyingAdapter.GetType().Name, message.Error);
else
{
var heartbeatAdapter = _hearbeatAdapters[innerAdapter];
foreach (var supportedMessage in innerAdapter.SupportedMessages)
{
_messageTypeAdapters.SafeAdd(supportedMessage).Add(heartbeatAdapter);
}
_connectedAdapters.Add(heartbeatAdapter);
}
message.Adapter = underlyingAdapter;
SendOutMessage(message);
}
private void ProcessDisconnectMessage(IMessageAdapter innerAdapter, DisconnectMessage message)
{
var underlyingAdapter = GetUnderlyingAdapter(innerAdapter);
if (message.Error != null)
this.AddErrorLog(LocalizedStrings.Str627Params, underlyingAdapter.GetType().Name, message.Error);
message.Adapter = underlyingAdapter;
SendOutMessage(message);
}
private void ProcessSubscriptionAction(IEnumerator<IMessageAdapter> enumerator, MarketDataMessage message, long originalTransactionId)
{
if (enumerator.MoveNext())
enumerator.Current.SendInMessage(message);
else
{
_subscriptionQueue.RemoveByValue(enumerator);
var key = _subscriptionKeys.TryGetValue(message.OriginalTransactionId);
if (key == null)
key = CreateKey(message);
else
_subscriptionKeys.Remove(originalTransactionId);
_subscriptionStates.Remove(key);
RaiseMarketDataMessage(null, originalTransactionId, new ArgumentException(LocalizedStrings.Str629Params.Put(key.Item1 + " " + key.Item2), nameof(message)), true);
}
}
private static SubscriptionInfo CreateKey(MarketDataMessage message)
{
return Tuple.Create(message.SecurityId, message.DataType, message.Arg, message.From, message.To, message.Count, message.MaxDepth);
}
private void ProcessMarketDataMessage(IMessageAdapter adapter, MarketDataMessage message)
{
var key = _subscriptionKeys.TryGetValue(message.OriginalTransactionId) ?? CreateKey(message);
var enumerator = _subscriptionQueue.TryGetValue(key);
var state = _subscriptionStates.TryGetValue2(key);
var error = message.Error;
var isOk = !message.IsNotSupported && error == null;
var isSubscribe = message.IsSubscribe;
switch (state)
{
case SubscriptionStates.Subscribed:
break;
case SubscriptionStates.Subscribing:
isSubscribe = true;
if (isOk)
{
_subscriptions.Add(key, adapter);
_subscriptionStates[key] = SubscriptionStates.Subscribed;
}
else if (error != null)
{
_subscriptions.Remove(key);
_subscriptionStates.Remove(key);
}
break;
case SubscriptionStates.Unsubscribing:
isSubscribe = false;
_subscriptions.Remove(key);
_subscriptionStates.Remove(key);
break;
case null:
if (isOk)
{
if (message.IsSubscribe)
{
_subscriptions.Add(key, adapter);
_subscriptionStates.Add(key, SubscriptionStates.Subscribed);
break;
}
}
_subscriptions.Remove(key);
_subscriptionStates.Remove(key);
break;
default:
throw new ArgumentOutOfRangeException();
}
if (message.IsNotSupported)
{
if (enumerator != null)
ProcessSubscriptionAction(enumerator, message, message.OriginalTransactionId);
else
{
if (error == null)
error = new InvalidOperationException(LocalizedStrings.Str633Params.Put(message.SecurityId, message.DataType));
}
}
_subscriptionQueue.Remove(key);
_subscriptionKeys.Remove(message.OriginalTransactionId);
RaiseMarketDataMessage(adapter, message.OriginalTransactionId, error, isSubscribe);
}
private void RaiseMarketDataMessage(IMessageAdapter adapter, long originalTransactionId, Exception error, bool isSubscribe)
{
SendOutMessage(new MarketDataMessage
{
OriginalTransactionId = originalTransactionId,
Error = error,
Adapter = adapter,
IsSubscribe = isSubscribe,
});
}
/// <summary>
/// To get adapters <see cref="IInnerAdapterList.SortedAdapters"/> sorted by the specified priority. By default, there is no sorting.
/// </summary>
/// <returns>Sorted adapters.</returns>
protected IEnumerable<IMessageAdapter> GetSortedAdapters()
{
return _innerAdapters.SortedAdapters;
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public override void Save(SettingsStorage storage)
{
lock (InnerAdapters.SyncRoot)
{
storage.SetValue(nameof(InnerAdapters), InnerAdapters.Select(a =>
{
var s = new SettingsStorage();
s.SetValue("AdapterType", a.GetType().GetTypeName(false));
s.SetValue("AdapterSettings", a.Save());
s.SetValue("Priority", InnerAdapters[a]);
return s;
}).ToArray());
}
base.Save(storage);
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public override void Load(SettingsStorage storage)
{
lock (InnerAdapters.SyncRoot)
{
InnerAdapters.Clear();
foreach (var s in storage.GetValue<IEnumerable<SettingsStorage>>(nameof(InnerAdapters)))
{
var adapter = s.GetValue<Type>("AdapterType").CreateInstance<IMessageAdapter>(TransactionIdGenerator);
adapter.Load(s.GetValue<SettingsStorage>("AdapterSettings"));
InnerAdapters[adapter] = s.GetValue<int>("Priority");
}
}
base.Load(storage);
}
/// <summary>
/// To release allocated resources.
/// </summary>
protected override void DisposeManaged()
{
_hearbeatAdapters.Values.ForEach(a => ((IMessageAdapter)a).Parent = null);
base.DisposeManaged();
}
IEnumerable<IMessageAdapter> IMessageAdapterProvider.Adapters => InnerAdapters;
IMessageAdapter IMessageAdapterProvider.GetAdapter(string portfolioName)
{
return Portfolios.TryGetValue(portfolioName);
}
void IMessageAdapterProvider.SetAdapter(string portfolioName, IMessageAdapter adapter)
{
Portfolios[portfolioName] = adapter;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Collections.Concurrent
{
public partial class BlockingCollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable, System.IDisposable
{
public BlockingCollection() { }
public BlockingCollection(System.Collections.Concurrent.IProducerConsumerCollection<T> collection) { }
public BlockingCollection(System.Collections.Concurrent.IProducerConsumerCollection<T> collection, int boundedCapacity) { }
public BlockingCollection(int boundedCapacity) { }
public int BoundedCapacity { get { throw null; } }
public int Count { get { throw null; } }
public bool IsAddingCompleted { get { throw null; } }
public bool IsCompleted { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Add(T item) { }
public void Add(T item, System.Threading.CancellationToken cancellationToken) { }
public static int AddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item) { throw null; }
public static int AddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, System.Threading.CancellationToken cancellationToken) { throw null; }
public void CompleteAdding() { }
public void CopyTo(T[] array, int index) { }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable() { throw null; }
public System.Collections.Generic.IEnumerable<T> GetConsumingEnumerable(System.Threading.CancellationToken cancellationToken) { throw null; }
System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator() { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T Take() { throw null; }
public T Take(System.Threading.CancellationToken cancellationToken) { throw null; }
public static int TakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item) { throw null; }
public static int TakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item, System.Threading.CancellationToken cancellationToken) { throw null; }
public T[] ToArray() { throw null; }
public bool TryAdd(T item) { throw null; }
public bool TryAdd(T item, int millisecondsTimeout) { throw null; }
public bool TryAdd(T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public bool TryAdd(T item, System.TimeSpan timeout) { throw null; }
public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item) { throw null; }
public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, int millisecondsTimeout) { throw null; }
public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public static int TryAddToAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, T item, System.TimeSpan timeout) { throw null; }
public bool TryTake(out T item) { throw null; }
public bool TryTake(out T item, int millisecondsTimeout) { throw null; }
public bool TryTake(out T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public bool TryTake(out T item, System.TimeSpan timeout) { throw null; }
public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item) { throw null; }
public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item, int millisecondsTimeout) { throw null; }
public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item, int millisecondsTimeout, System.Threading.CancellationToken cancellationToken) { throw null; }
public static int TryTakeFromAny(System.Collections.Concurrent.BlockingCollection<T>[] collections, out T item, System.TimeSpan timeout) { throw null; }
}
public partial class ConcurrentBag<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ConcurrentBag() { }
public ConcurrentBag(System.Collections.Generic.IEnumerable<T> collection) { }
public int Count { get { throw null; } }
public bool IsEmpty { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Add(T item) { }
public void Clear() { }
public void CopyTo(T[] array, int index) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T[] ToArray() { throw null; }
public bool TryPeek(out T result) { throw null; }
public bool TryTake(out T result) { throw null; }
}
public partial class ConcurrentDictionary<TKey, TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IDictionary<TKey, TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey, TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>, System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public ConcurrentDictionary() { }
public ConcurrentDictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection) { }
public ConcurrentDictionary(System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public ConcurrentDictionary(System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public ConcurrentDictionary(int concurrencyLevel, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey, TValue>> collection, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public ConcurrentDictionary(int concurrencyLevel, int capacity) { }
public ConcurrentDictionary(int concurrencyLevel, int capacity, System.Collections.Generic.IEqualityComparer<TKey> comparer) { }
public int Count { get { throw null; } }
public bool IsEmpty { get { throw null; } }
public TValue this[TKey key] { get { throw null; } set { } }
public System.Collections.Generic.ICollection<TKey> Keys { get { throw null; } }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { throw null; } }
System.Collections.Generic.IEnumerable<TKey> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Keys { get { throw null; } }
System.Collections.Generic.IEnumerable<TValue> System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>.Values { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
bool System.Collections.IDictionary.IsFixedSize { get { throw null; } }
bool System.Collections.IDictionary.IsReadOnly { get { throw null; } }
object System.Collections.IDictionary.this[object key] { get { throw null; } set { } }
System.Collections.ICollection System.Collections.IDictionary.Keys { get { throw null; } }
System.Collections.ICollection System.Collections.IDictionary.Values { get { throw null; } }
public System.Collections.Generic.ICollection<TValue> Values { get { throw null; } }
public TValue AddOrUpdate(TKey key, System.Func<TKey, TValue> addValueFactory, System.Func<TKey, TValue, TValue> updateValueFactory) { throw null; }
public TValue AddOrUpdate(TKey key, TValue addValue, System.Func<TKey, TValue, TValue> updateValueFactory) { throw null; }
public TValue AddOrUpdate<TArg>(TKey key, System.Func<TKey, TArg, TValue> addValueFactory, System.Func<TKey, TValue, TArg, TValue> updateValueFactory, TArg factoryArgument) { throw null; }
public void Clear() { }
public bool ContainsKey(TKey key) { throw null; }
public System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<TKey, TValue>> GetEnumerator() { throw null; }
public TValue GetOrAdd(TKey key, System.Func<TKey, TValue> valueFactory) { throw null; }
public TValue GetOrAdd(TKey key, TValue value) { throw null; }
public TValue GetOrAdd<TArg>(TKey key, System.Func<TKey, TArg, TValue> valueFactory, TArg factoryArgument) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo(System.Collections.Generic.KeyValuePair<TKey, TValue>[] array, int index) { }
bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove(System.Collections.Generic.KeyValuePair<TKey, TValue> keyValuePair) { throw null; }
void System.Collections.Generic.IDictionary<TKey,TValue>.Add(TKey key, TValue value) { }
bool System.Collections.Generic.IDictionary<TKey,TValue>.Remove(TKey key) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object key, object value) { }
bool System.Collections.IDictionary.Contains(object key) { throw null; }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { throw null; }
void System.Collections.IDictionary.Remove(object key) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public System.Collections.Generic.KeyValuePair<TKey, TValue>[] ToArray() { throw null; }
public bool TryAdd(TKey key, TValue value) { throw null; }
public bool TryGetValue(TKey key, out TValue value) { throw null; }
public bool TryRemove(TKey key, out TValue value) { throw null; }
public bool TryUpdate(TKey key, TValue newValue, TValue comparisonValue) { throw null; }
}
public partial class ConcurrentQueue<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ConcurrentQueue() { }
public ConcurrentQueue(System.Collections.Generic.IEnumerable<T> collection) { }
public int Count { get { throw null; } }
public bool IsEmpty { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Clear() { }
public void CopyTo(T[] array, int index) { }
public void Enqueue(T item) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; }
bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryTake(out T item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T[] ToArray() { throw null; }
public bool TryDequeue(out T result) { throw null; }
public bool TryPeek(out T result) { throw null; }
}
public partial class ConcurrentStack<T> : System.Collections.Concurrent.IProducerConsumerCollection<T>, System.Collections.Generic.IEnumerable<T>, System.Collections.Generic.IReadOnlyCollection<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
public ConcurrentStack() { }
public ConcurrentStack(System.Collections.Generic.IEnumerable<T> collection) { }
public int Count { get { throw null; } }
public bool IsEmpty { get { throw null; } }
bool System.Collections.ICollection.IsSynchronized { get { throw null; } }
object System.Collections.ICollection.SyncRoot { get { throw null; } }
public void Clear() { }
public void CopyTo(T[] array, int index) { }
public System.Collections.Generic.IEnumerator<T> GetEnumerator() { throw null; }
public void Push(T item) { }
public void PushRange(T[] items) { }
public void PushRange(T[] items, int startIndex, int count) { }
bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryAdd(T item) { throw null; }
bool System.Collections.Concurrent.IProducerConsumerCollection<T>.TryTake(out T item) { throw null; }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
public T[] ToArray() { throw null; }
public bool TryPeek(out T result) { throw null; }
public bool TryPop(out T result) { throw null; }
public int TryPopRange(T[] items) { throw null; }
public int TryPopRange(T[] items, int startIndex, int count) { throw null; }
}
[System.FlagsAttribute]
public enum EnumerablePartitionerOptions
{
NoBuffering = 1,
None = 0,
}
public partial interface IProducerConsumerCollection<T> : System.Collections.Generic.IEnumerable<T>, System.Collections.ICollection, System.Collections.IEnumerable
{
void CopyTo(T[] array, int index);
T[] ToArray();
bool TryAdd(T item);
bool TryTake(out T item);
}
public abstract partial class OrderablePartitioner<TSource> : System.Collections.Concurrent.Partitioner<TSource>
{
protected OrderablePartitioner(bool keysOrderedInEachPartition, bool keysOrderedAcrossPartitions, bool keysNormalized) { }
public bool KeysNormalized { get { throw null; } }
public bool KeysOrderedAcrossPartitions { get { throw null; } }
public bool KeysOrderedInEachPartition { get { throw null; } }
public override System.Collections.Generic.IEnumerable<TSource> GetDynamicPartitions() { throw null; }
public virtual System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<long, TSource>> GetOrderableDynamicPartitions() { throw null; }
public abstract System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<System.Collections.Generic.KeyValuePair<long, TSource>>> GetOrderablePartitions(int partitionCount);
public override System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<TSource>> GetPartitions(int partitionCount) { throw null; }
}
public static partial class Partitioner
{
public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<int, int>> Create(int fromInclusive, int toExclusive) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<int, int>> Create(int fromInclusive, int toExclusive, int rangeSize) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<long, long>> Create(long fromInclusive, long toExclusive) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<System.Tuple<long, long>> Create(long fromInclusive, long toExclusive, long rangeSize) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IEnumerable<TSource> source) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IEnumerable<TSource> source, System.Collections.Concurrent.EnumerablePartitionerOptions partitionerOptions) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(System.Collections.Generic.IList<TSource> list, bool loadBalance) { throw null; }
public static System.Collections.Concurrent.OrderablePartitioner<TSource> Create<TSource>(TSource[] array, bool loadBalance) { throw null; }
}
public abstract partial class Partitioner<TSource>
{
protected Partitioner() { }
public virtual bool SupportsDynamicPartitions { get { throw null; } }
public virtual System.Collections.Generic.IEnumerable<TSource> GetDynamicPartitions() { throw null; }
public abstract System.Collections.Generic.IList<System.Collections.Generic.IEnumerator<TSource>> GetPartitions(int partitionCount);
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Text;
using Microsoft.Test.ModuleCore;
using Xunit;
namespace CoreXml.Test.XLinq
{
public partial class FunctionalTests : TestModule
{
// Type is CoreXml.Test.XLinq.FunctionalTests
[Fact]
public static void RunTests()
{
TestInput.CommandLine = "";
FunctionalTests module = new FunctionalTests();
module.Init();
//for class EventsTests
{
module.AddChild(new EventsTests() { Attribute = new TestCaseAttribute() { Name = "Events", Desc = "XLinq Events Tests" } });
}
module.Execute();
Assert.Equal(0, module.FailCount);
}
public partial class EventsTests : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests
// Test Case
public override void AddChildren()
{
this.AddChild(new EventsAddBeforeSelf() { Attribute = new TestCaseAttribute() { Name = "XNode.AddBeforeSelf()" } });
this.AddChild(new EventsAddAfterSelf() { Attribute = new TestCaseAttribute() { Name = "XNode.AddAfterSelf()" } });
this.AddChild(new EventsAddFirst() { Attribute = new TestCaseAttribute() { Name = "XContainer.AddFirst()" } });
this.AddChild(new EventsAdd() { Attribute = new TestCaseAttribute() { Name = "XContainer.Add()" } });
this.AddChild(new EventsXElementName() { Attribute = new TestCaseAttribute() { Name = "XObject.Name" } });
this.AddChild(new EventsSpecialCases() { Attribute = new TestCaseAttribute() { Name = "SpecialCases" } });
this.AddChild(new EventsRemove() { Attribute = new TestCaseAttribute() { Name = "XNode.Remove()" } });
this.AddChild(new EventsRemoveNodes() { Attribute = new TestCaseAttribute() { Name = "XContainer.RemoveNodes()" } });
this.AddChild(new EventsRemoveAll() { Attribute = new TestCaseAttribute() { Name = "XElement.RemoveAll()" } });
this.AddChild(new EventsReplaceWith() { Attribute = new TestCaseAttribute() { Name = "XNode.ReplaceWith()" } });
this.AddChild(new EventsReplaceNodes() { Attribute = new TestCaseAttribute() { Name = "XContainer.ReplaceNodes()" } });
this.AddChild(new EvensReplaceAttributes() { Attribute = new TestCaseAttribute() { Name = "XElement.ReplaceAttributes()" } });
this.AddChild(new EventsReplaceAll() { Attribute = new TestCaseAttribute() { Name = "XElement.ReplaceAll()" } });
this.AddChild(new EventsXObjectValue() { Attribute = new TestCaseAttribute() { Name = "XObjects.Value" } });
this.AddChild(new EventsXElementValue() { Attribute = new TestCaseAttribute() { Name = "XElement.Value" } });
this.AddChild(new EventsXAttributeValue() { Attribute = new TestCaseAttribute() { Name = "XAttribute.Value" } });
this.AddChild(new EventsXAttributeSetValue() { Attribute = new TestCaseAttribute() { Name = "XAttribute.SetValue" } });
this.AddChild(new EventsXElementSetValue() { Attribute = new TestCaseAttribute() { Name = "XElement.SetValue" } });
this.AddChild(new EventsXElementSetAttributeValue() { Attribute = new TestCaseAttribute() { Name = "XElement.SetAttributeValue" } });
this.AddChild(new EventsXElementSetElementValue() { Attribute = new TestCaseAttribute() { Name = "XElement.SetElementValue" } });
}
public partial class EventsBase : XLinqTestCase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsBase
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsAddBeforeSelf : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsAddBeforeSelf
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(AddNull) { Attribute = new VariationAttribute("XElement - Add null") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("XElement - Working on the text nodes 1.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("XElement - Working on the text nodes 2.") { Priority = 1 } });
}
}
public partial class EventsAddAfterSelf : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsAddAfterSelf
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(AddNull) { Attribute = new VariationAttribute("XElement-Add null") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("XElement - Working on the text nodes 1.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("XElement - Working on the text nodes 2.") { Priority = 1 } });
}
}
public partial class EventsAddFirst : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsAddFirst
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(AddNull) { Attribute = new VariationAttribute("XElement - Add null") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("XElement - Working on the text nodes 1.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("XElement - Working on the text nodes 2.") { Priority = 1 } });
this.AddChild(new TestVariation(StringContent) { Attribute = new VariationAttribute("XElement - Change content in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(ParentedXNode) { Attribute = new VariationAttribute("XElement - Change xnode's parent in the pre-event handler") { Priority = 1 } });
}
}
public partial class EventsAdd : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsAdd
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(XAttributeAddAtDeepLevel) { Attribute = new VariationAttribute("XAttribute - Add at each level, nested elements") { Priority = 1 } });
this.AddChild(new TestVariation(XElementAddAtDeepLevel) { Attribute = new VariationAttribute("XElement - Add at each level, nested elements") { Priority = 1 } });
this.AddChild(new TestVariation(WorkTextNodes) { Attribute = new VariationAttribute("XElement - Text node incarnation.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("XElement - Working on the text nodes 1.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("XElement - Working on the text nodes 2.") { Priority = 1 } });
this.AddChild(new TestVariation(StringContent) { Attribute = new VariationAttribute("XElement - Change content in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(ParentedXNode) { Attribute = new VariationAttribute("XElement - Change xnode's parent in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(ParentedAttribute) { Attribute = new VariationAttribute("XElement - Change attribute's parent in the pre-event handler") { Priority = 1 } });
}
}
public partial class EventsXElementName : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXElementName
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(PIVariation) { Attribute = new VariationAttribute("XProcessingInstruction - Name") { Priority = 0 } });
this.AddChild(new TestVariation(DocTypeVariation) { Attribute = new VariationAttribute("XDocumentType - Name") { Priority = 0 } });
}
}
public partial class EventsSpecialCases : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsSpecialCases
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(XElementRemoveNullEventListner) { Attribute = new VariationAttribute("Adding, Removing null listeners") { Priority = 1 } });
this.AddChild(new TestVariation(XElementRemoveBothEventListners) { Attribute = new VariationAttribute("Remove both event listeners") { Priority = 1 } });
this.AddChild(new TestVariation(AddListnerInPreEvent) { Attribute = new VariationAttribute("Add Changed listner in pre-event") { Priority = 1 } });
this.AddChild(new TestVariation(XElementAddRemoveEventListners) { Attribute = new VariationAttribute("Add and remove event listners") { Priority = 1 } });
this.AddChild(new TestVariation(XElementAttachAtEachLevel) { Attribute = new VariationAttribute("Attach listners at each level, nested elements") { Priority = 1 } });
this.AddChild(new TestVariation(XElementPreException) { Attribute = new VariationAttribute("Exception in PRE Event Handler") { Priority = 2 } });
this.AddChild(new TestVariation(XElementPostException) { Attribute = new VariationAttribute("Exception in POST Event Handler") { Priority = 2 } });
}
}
public partial class EventsRemove : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsRemove
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(WorkOnTextNodes1) { Attribute = new VariationAttribute("XElement - Working on the text nodes 1.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes2) { Attribute = new VariationAttribute("XElement - Working on the text nodes 2.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes3) { Attribute = new VariationAttribute("XElement - Working on the text nodes 3.") { Priority = 1 } });
this.AddChild(new TestVariation(WorkOnTextNodes4) { Attribute = new VariationAttribute("XElement - Working on the text nodes 4.") { Priority = 1 } });
this.AddChild(new TestVariation(XAttributeRemoveOneByOne) { Attribute = new VariationAttribute("XAttribute - Remove one attribute at a time") { Priority = 1 } });
this.AddChild(new TestVariation(XElementRemoveOneByOne) { Attribute = new VariationAttribute("XElement - Remove one element (with children) at a time") { Priority = 1 } });
this.AddChild(new TestVariation(XAttributeRemoveSeq) { Attribute = new VariationAttribute("Remove Sequence - IEnumerable<XAttribute>") { Priority = 1 } });
this.AddChild(new TestVariation(XElementRemoveSeq) { Attribute = new VariationAttribute("Remove Sequence - IEnumerable<XElement>") { Priority = 1 } });
this.AddChild(new TestVariation(ParentedXNode) { Attribute = new VariationAttribute("XElement - Change xnode's parent in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(ParentedAttribute) { Attribute = new VariationAttribute("XElement - Change attribute's parent in the pre-event handler") { Priority = 1 } });
}
}
public partial class EventsRemoveNodes : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsRemoveNodes
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(RemoveNodesBug) { Attribute = new VariationAttribute("XElement - empty element special case <A></A>") { Priority = 1 } });
this.AddChild(new TestVariation(ChangeContentBeforeRemove) { Attribute = new VariationAttribute("XElement - Change node value in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(RemoveNodeInPreEvent) { Attribute = new VariationAttribute("XElement - Change nodes in the pre-event handler") { Priority = 1 } });
this.AddChild(new TestVariation(RemoveAttributeInPreEvent) { Attribute = new VariationAttribute("XElement - Change attributes in the pre-event handler") { Priority = 1 } });
}
}
public partial class EventsRemoveAll : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsRemoveAll
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsReplaceWith : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsReplaceWith
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsReplaceNodes : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsReplaceNodes
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(ReplaceNodes) { Attribute = new VariationAttribute("XElement - Replace Nodes") { Priority = 1 } });
this.AddChild(new TestVariation(ReplaceWithIEnum) { Attribute = new VariationAttribute("XElement - Replace with IEnumberable") { Priority = 1 } });
}
}
public partial class EvensReplaceAttributes : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EvensReplaceAttributes
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsReplaceAll : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsReplaceAll
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(ElementWithAttributes) { Attribute = new VariationAttribute("Element with attributes, with Element with attributes") { Priority = 1 } });
}
}
public partial class EventsXObjectValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXObjectValue
// Test Case
public override void AddChildren()
{
this.AddChild(new TestVariation(XTextValue) { Attribute = new VariationAttribute("XText - change value") { Priority = 0 } });
this.AddChild(new TestVariation(XCDataValue) { Attribute = new VariationAttribute("XCData - change value") { Priority = 0 } });
this.AddChild(new TestVariation(XCommentValue) { Attribute = new VariationAttribute("XComment - change value") { Priority = 0 } });
this.AddChild(new TestVariation(XPIValue) { Attribute = new VariationAttribute("XProcessingInstruction - change value") { Priority = 0 } });
this.AddChild(new TestVariation(XDocTypePublicID) { Attribute = new VariationAttribute("XDocumentType - change public Id") { Priority = 0 } });
this.AddChild(new TestVariation(XDocTypeSystemID) { Attribute = new VariationAttribute("XDocumentType - change system Id") { Priority = 0 } });
this.AddChild(new TestVariation(XDocTypeInternalSubset) { Attribute = new VariationAttribute("XDocumentType - change internal subset") { Priority = 0 } });
}
}
public partial class EventsXElementValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXElementValue
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsXAttributeValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXAttributeValue
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsXAttributeSetValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXAttributeSetValue
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsXElementSetValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXElementSetValue
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsXElementSetAttributeValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXElementSetAttributeValue
// Test Case
public override void AddChildren()
{
}
}
public partial class EventsXElementSetElementValue : EventsBase
{
// Type is CoreXml.Test.XLinq.FunctionalTests+EventsTests+EventsXElementSetElementValue
// Test Case
public override void AddChildren()
{
}
}
}
}
}
| |
//
// Mono.Facebook.FacebookSession.cs:
//
// Authors:
// Thomas Van Machelen (thomas.vanmachelen@gmail.com)
// George Talusan (george@convolve.ca)
//
// (C) Copyright 2007 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.Xml;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Linq;
using Mono.Facebook.Schemas;
namespace Mono.Facebook
{
public class FacebookSession
{
Util util;
SessionInfo session_info;
string auth_token;
internal string SessionKey {
get { return session_info.session_key; }
}
internal Util Util
{
get { return util; }
}
// use this for plain sessions
public FacebookSession (string api_key, string shared_secret)
{
util = new Util (api_key, shared_secret);
}
// use this if you want to re-start an infinite session
public FacebookSession (string api_key, SessionInfo session_info)
: this (api_key, session_info.secret)
{
this.session_info = session_info;
}
public Uri CreateToken ()
{
XmlDocument doc = util.GetResponse ("facebook.auth.createToken");
auth_token = doc.InnerText;
return new Uri (string.Format ("http://www.facebook.com/login.php?api_key={0}&v=1.0&auth_token={1}", util.ApiKey, auth_token));
}
public Uri GetGrantUri (string permission)
{
return new Uri(string.Format("http://www.facebook.com/authorize.php?api_key={0}&v=1.0&ext_perm={1}", util.ApiKey, permission));
}
public bool HasAppPermission(string permission)
{
return util.GetBoolResponse("facebook.users.hasAppPermission",
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("ext_perm", permission));
}
public bool RevokeAppPermission(string permission)
{
return util.GetBoolResponse
("facebook.auth.revokeExtendedPermission",
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("perm", permission));
}
public SessionInfo GetSession ()
{
return GetSessionFromToken(auth_token);
}
public SessionInfo GetSessionFromToken(string auth_token)
{
this.session_info = util.GetResponse<SessionInfo>("facebook.auth.getSession",
FacebookParam.Create("auth_token", auth_token));
this.util.SharedSecret = session_info.secret;
this.auth_token = string.Empty;
return session_info;
}
public Album[] GetAlbums ()
{
try {
var rsp = util.GetResponse<AlbumsResponse> ("facebook.photos.getAlbums",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
var profile_rsp = util.GetResponse<AlbumsResponse> ("facebook.photos.getAlbums",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("aid", -3));
// Filters out Profile pictures album, can't upload there.
return rsp.albums.Where ((a) => a.aid != profile_rsp.album [0].aid).ToArray ();
} catch (FormatException) {
return new Album[0];
}
}
public Album CreateAlbum (string name, string description, string location)
{
// create parameter list
List<FacebookParam> param_list = new List<FacebookParam> ();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
param_list.Add (FacebookParam.Create ("name", name));
if (description != null && description != string.Empty)
param_list.Add (FacebookParam.Create ("description", description));
if (location != null && location != string.Empty)
param_list.Add (FacebookParam.Create ("location", location));
// create the albums
Album new_album = util.GetResponse<Album> ("facebook.photos.createAlbum", param_list.ToArray ());
new_album.Session = this;
// return
return new_album;
}
public Group[] GetGroups ()
{
return this.GetGroups (session_info.uid, null);
}
public Group[] GetGroups (long? uid, long[] gids)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uid != null)
param_list.Add (FacebookParam.Create ("uid", uid));
if (gids != null)
param_list.Add (FacebookParam.Create ("gids", gids));
GroupsResponse rsp = util.GetResponse<GroupsResponse>("facebook.groups.get", param_list.ToArray ());
foreach (Group gr in rsp.Groups)
gr.Session = this;
return rsp.Groups;
}
public Event[] GetEvents ()
{
return GetEvents (session_info.uid, null, 0, 0, null);
}
public Event[] GetEvents (long? uid, long[] eids, long start_time, long end_time, string rsvp_status)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uid != null)
param_list.Add (FacebookParam.Create ("uid", uid));
if (eids != null)
param_list.Add (FacebookParam.Create ("eids", eids));
param_list.Add (FacebookParam.Create ("start_time", start_time));
param_list.Add (FacebookParam.Create ("end_time", start_time));
if (rsvp_status != null)
param_list.Add (FacebookParam.Create ("rsvp_status", rsvp_status));
EventsResponse rsp = util.GetResponse<EventsResponse>("facebook.events.get", param_list.ToArray ());
foreach (Event evt in rsp.Events)
evt.Session = this;
return rsp.Events;
}
public User GetUserInfo (long uid)
{
User[] users = this.GetUserInfo (new long[1] { uid }, User.FIELDS);
if (users.Length < 1)
return null;
return users[0];
}
public User[] GetUserInfo (long[] uids, string[] fields)
{
List<FacebookParam> param_list = new List<FacebookParam>();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uids == null || uids.Length == 0)
throw new Exception ("uid not provided");
param_list.Add (FacebookParam.Create ("uids", uids));
param_list.Add (FacebookParam.Create ("fields", fields));
UserInfoResponse rsp = util.GetResponse<UserInfoResponse>("facebook.users.getInfo", param_list.ToArray ());
return rsp.Users;
}
public Me GetLoggedInUser ()
{
return new Me (session_info.uid, this);
}
public Notifications GetNotifications ()
{
Notifications notifications = util.GetResponse<Notifications>("facebook.notifications.get",
FacebookParam.Create ("uid", session_info.uid),
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
foreach (Friend f in notifications.FriendRequests)
f.Session = this;
return notifications;
}
public Friend[] GetFriends ()
{
FriendsResponse response = Util.GetResponse<FriendsResponse>("facebook.friends.get",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks));
Friend[] friends = new Friend[response.UIds.Length];
for (int i = 0; i < friends.Length; i++)
friends[i] = new Friend (response.UIds[i], this);
return friends;
}
public bool AreFriends (Friend friend1, Friend friend2)
{
return AreFriends (friend1.UId, friend2.UId);
}
public bool AreFriends (long uid1, long uid2)
{
AreFriendsResponse response = Util.GetResponse<AreFriendsResponse>("facebook.friends.areFriends",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("uids1", uid1),
FacebookParam.Create ("uids2", uid2));
return response.friend_infos[0].AreFriends;
}
public FriendInfo[] AreFriends (long[] uids1, long[] uids2)
{
List<FacebookParam> param_list = new List<FacebookParam> ();
param_list.Add (FacebookParam.Create ("session_key", session_info.session_key));
param_list.Add (FacebookParam.Create ("call_id", DateTime.Now.Ticks));
if (uids1 == null || uids1.Length == 0)
throw new Exception ("uids1 not provided");
if (uids2 == null || uids2.Length == 0)
throw new Exception ("uids2 not provided");
param_list.Add (FacebookParam.Create ("uids1", uids1));
param_list.Add (FacebookParam.Create ("uids2", uids2));
AreFriendsResponse rsp = util.GetResponse<AreFriendsResponse> ("facebook.friends.areFriends", param_list.ToArray ());
return rsp.friend_infos;
}
public XmlDocument Query (string sql_query)
{
XmlDocument doc = Util.GetResponse ("facebook.fql.query",
FacebookParam.Create ("session_key", session_info.session_key),
FacebookParam.Create ("call_id", DateTime.Now.Ticks),
FacebookParam.Create ("query", sql_query));
return doc;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace EmergeTk.Model.Security
{
public class User : AbstractRecord
{
private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(User));
private static readonly EmergeTkLog securityViolationLog = EmergeTkLogManager.GetLogger("PotentialOnlyCSRF");
public static List<User> activeUsers = new List<User>();
private static readonly long loginTokenLifetime = Setting.GetValueT<long>("LoginTokenLifetime", 1440);
private static readonly string preventionReferrerHost = Setting.GetValueT<string>("CSRFPreventionReferrerHost");
static Type defaultType;
static User()
{
defaultType = typeof(User);
//would be nice to listen to load events here.
}
public User()
{
byte[] bytes = new byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(bytes);
this.salt = (int)BitConverter.ToInt32(bytes, 0);
}
private string ComputeSaltedPassword(string plainTextPassword)
{
UnicodeEncoding encoder = new UnicodeEncoding();
byte[] passwordBytes = encoder.GetBytes(plainTextPassword);
byte[] saltBytes = BitConverter.GetBytes(this.Salt);
byte[] saltedPasswordBytes = new byte[passwordBytes.Length + saltBytes.Length];
passwordBytes.CopyTo(saltedPasswordBytes, 0);
saltBytes.CopyTo(saltedPasswordBytes, passwordBytes.Length);
SHA512 hasher = SHA512.Create();
byte[] finalHash = hasher.ComputeHash(saltedPasswordBytes);
return Convert.ToBase64String(finalHash);
}
private string name;
public string Name
{
get { return this.name; }
set
{
if (!String.IsNullOrEmpty(value))
{
this.name = value;
}
}
}
public string PlainTextPassword
{
get { return String.Empty; }
set
{
if (!String.IsNullOrEmpty(value))
{
this.password = this.ComputeSaltedPassword(value);
}
}
}
private string password;
public string Password
{
get { return this.password; }
set
{
if (!String.IsNullOrEmpty(value))
{
this.password = value;
}
}
}
private int salt = -1;
public int Salt
{
get { return this.salt; }
set { this.salt = value; }
}
private string sessionToken;
public string SessionToken
{
get { return this.sessionToken; }
set { this.sessionToken = value; }
}
private RecordList<Role> roles;
bool rolesChanged = false;
public RecordList<Role> Roles
{
get
{
if (this.roles == null)
{
this.lazyLoadProperty<Role>("Roles");
}
return this.roles;
}
set {
this.roles = value;
}
}
public string RoleString
{
get
{
return Util.Join(Roles.ToStringArray("Name"));
}
}
public IRecordList<Group> GetGroups()
{
return this.LoadParents<Group>(ColumnInfoManager.RequestColumn<Group>("Users"));
}
public virtual bool CheckPermission(Permission p)
{
foreach (Role role in this.Roles)
{
if (role.Permissions.Contains(p))
{
return true;
}
}
return false;
}
public RecordList<Permission> Permissions
{
get {
RecordList<Permission> permissions = new EmergeTk.Model.RecordList<Permission>();
foreach( Role role in this.Roles )
{
foreach( Permission p in role.Permissions )
permissions.Add( p );
}
return permissions;
}
}
public static Type DefaultType {
get {
return defaultType;
}
set {
defaultType = value;
}
}
private bool passwordIsVerified;
public bool PasswordIsVerified {
get {
return passwordIsVerified;
}
set {
passwordIsVerified = value;
}
}
private DateTime? lastLoginDate;
public DateTime? LastLoginDate
{
get
{
return lastLoginDate;
}
set
{
lastLoginDate = value;
}
}
private DateTime? currentLoginDate;
public DateTime? CurrentLoginDate
{
get
{
return currentLoginDate;
}
set
{
if (!Loading)
LastLoginDate = currentLoginDate;
currentLoginDate = value;
}
}
public void GenerateAndSetNewSessionToken()
{
this.SessionToken = Util.GetBase32Guid();
}
public override void Save(bool SaveChildren, bool IncrementVersion, System.Data.Common.DbConnection conn)
{
//log.Debug("Executing User Save override - this.roles=", this.Roles);
base.Save(SaveChildren, IncrementVersion, conn);
if( rolesChanged )
{
this.SaveRelations("Roles");
foreach( User u in activeUsers )
{
if( u == this )
u.roles = this.roles.Copy() as RecordList<Role>;
}
}
}
private const int newPasswordLength = 8;
public static string GetNewDefaultPassword()
{
byte[] passwordBytes = new byte[User.newPasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(passwordBytes);
return Convert.ToBase64String(passwordBytes);
}
public override string ToString()
{
return name;
}
public static bool IsRoot
{
get
{
return Current != null && Current.CheckPermission(Permission.Root);
}
}
public static User Current
{
get
{
if( HttpContext.Current != null && HttpContext.Current.Items["user"] != null )
{
return (User)HttpContext.Current.Items["user"];
}
User u = null;
if (HttpContext.Current != null)
{
u = FindBySessionToken();
HttpContext.Current.Items["user"] = u;
}
return u;
}
set
{
if( HttpContext.Current != null )
HttpContext.Current.Items["user"] = value;
}
}
public void SetLoginCookie()
{
//log.Debug("setting login cookie");
HttpCookie userIdCookie = new HttpCookie("UserId", Id.ToString());
userIdCookie.Expires = DateTime.UtcNow.AddYears(1);
HttpContext.Current.Response.Cookies.Add(userIdCookie);
SetRoleCookie(Roles.Count > 0 ? Roles.JoinToString(",") : "");
//throw new Exception("setting login cookie");
}
public void SetRoleCookie(string role)
{
HttpCookie sessionCookie = new HttpCookie("Role", role);
sessionCookie.Expires = DateTime.UtcNow.AddDays(1);
HttpContext.Current.Response.Cookies.Add(sessionCookie);
}
public static string GetRequestToken()
{
if (HttpContext.Current == null)
return null;
else
return HttpContext.Current.Request.Headers["x-LoginToken"];
}
public static User GetUserFromTokenHeader()
{
User user = null;
string token = GetRequestToken();
if (!String.IsNullOrEmpty(token))
{
user = User.FindBySessionToken(token);
}
return user;
}
public static void RegisterActiveUser( User u )
{
//note: only call RegisterActiveUser if you wish the user to receive role change notifications.
activeUsers.Add( u );
}
public static void UnregisterActiveUser( User u )
{
while( activeUsers.Contains( u ) )
{
activeUsers.Remove( u );
}
}
public static User LoginUser(string username, string password)
{
// TODO: do we need to capture TableNotFoundException? right now the Login widget does that
User user = AbstractRecord.Load(defaultType, new FilterInfo("Name", username )) as User;
if (user != null)
{
if (user.ComputeSaltedPassword(password) == user.Password)
{
//only provide a new session token if there is none currently.
//to allow multiple logins.
if (string.IsNullOrEmpty (user.SessionToken))
{
user.GenerateAndSetNewSessionToken();
user.CurrentLoginDate = DateTime.UtcNow;
}
user.Save();
return user;
}
}
return null;
}
public static User FindBySessionToken()
{
return GetUserFromTokenHeader();
}
public static User FindBySessionToken(string token)
{
User user = AbstractRecord.Load(defaultType, new FilterInfo("SessionToken", token )) as User;
return user;
}
public static void CheckReferrerHost()
{
if (!String.IsNullOrEmpty(preventionReferrerHost) && HttpContext.Current != null)
{
string referrer = HttpContext.Current.Request.UrlReferrer.Host;
if (!String.IsNullOrEmpty(referrer) && preventionReferrerHost != referrer)
{
securityViolationLog.ErrorFormat("HttpContext Referring Domain Host '{0}' does not match configuration '{1}'. Request Host:{2}", referrer, preventionReferrerHost, HttpContext.Current.Request.UserHostAddress);
throw new UnauthorizedAccessException("Invalid Referring Domain Host.");
}
}
}
public static void AuthenticateUser()
{
CheckReferrerHost();
string token = GetRequestToken();
string host = HttpContext.Current != null ? HttpContext.Current.Request.UserHostAddress : null;
User user = User.Current;
if (null != user)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["UserId"];
if (null != cookie && !String.IsNullOrEmpty(cookie.Value))
{
if (user.Id != Convert.ToInt32(cookie.Value))
{
securityViolationLog.ErrorFormat("User {0} with given token {1} does not match supplied cookie {2}. Request Host:{3}", user.Id, token, cookie.Value, host);
throw new UnauthorizedAccessException("Invalid Credentials.");
}
}
else
{//could this EVER be ok or should we prevent access?
securityViolationLog.ErrorFormat("Unusual! Missing UserId cookie. Why? User {0} with given token {1}. Request Host:{2}", user.Id, token, host);
throw new UnauthorizedAccessException("Invalid Credentials.");
}
if (user.CurrentLoginDate.Value.AddMinutes(loginTokenLifetime) < DateTime.UtcNow)
{//blank out the session thus forcing user to login and get NEW session
user.SessionToken = String.Empty;
user.Save();
log.Info(string.Format("User session has timed out for {0}. Id:{1}", user.Name, user.Id));
throw new TimeoutException("Expired Credentials.");
}
}
else
{
securityViolationLog.ErrorFormat("No user found with given token: {0}. OK during Login request only. Request Host:{1}", token, host);
throw new UnauthorizedAccessException("Invalid Credentials.");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System
{
public abstract partial class Type : MemberInfo, IReflect
{
protected Type() { }
public override MemberTypes MemberType => MemberTypes.TypeInfo;
public new Type GetType() => base.GetType();
public abstract string? Namespace { get; }
public abstract string? AssemblyQualifiedName { get; }
public abstract string? FullName { get; }
public abstract Assembly Assembly { get; }
public new abstract Module Module { get; }
public bool IsNested => DeclaringType != null;
public override Type? DeclaringType => null;
public virtual MethodBase? DeclaringMethod => null;
public override Type? ReflectedType => null;
public abstract Type UnderlyingSystemType { get; }
public virtual bool IsTypeDefinition => throw NotImplemented.ByDesign;
public bool IsArray => IsArrayImpl();
protected abstract bool IsArrayImpl();
public bool IsByRef => IsByRefImpl();
protected abstract bool IsByRefImpl();
public bool IsPointer => IsPointerImpl();
protected abstract bool IsPointerImpl();
public virtual bool IsConstructedGenericType => throw NotImplemented.ByDesign;
public virtual bool IsGenericParameter => false;
public virtual bool IsGenericTypeParameter => IsGenericParameter && DeclaringMethod is null;
public virtual bool IsGenericMethodParameter => IsGenericParameter && DeclaringMethod != null;
public virtual bool IsGenericType => false;
public virtual bool IsGenericTypeDefinition => false;
public virtual bool IsSZArray => throw NotImplemented.ByDesign;
public virtual bool IsVariableBoundArray => IsArray && !IsSZArray;
public virtual bool IsByRefLike => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public bool HasElementType => HasElementTypeImpl();
protected abstract bool HasElementTypeImpl();
public abstract Type? GetElementType();
public virtual int GetArrayRank() => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public virtual Type GetGenericTypeDefinition() => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public virtual Type[] GenericTypeArguments => (IsGenericType && !IsGenericTypeDefinition) ? GetGenericArguments() : Array.Empty<Type>();
public virtual Type[] GetGenericArguments() => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public virtual int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
public virtual GenericParameterAttributes GenericParameterAttributes => throw new NotSupportedException();
public virtual Type[] GetGenericParameterConstraints()
{
if (!IsGenericParameter)
throw new InvalidOperationException(SR.Arg_NotGenericParameter);
throw new InvalidOperationException();
}
public TypeAttributes Attributes => GetAttributeFlagsImpl();
protected abstract TypeAttributes GetAttributeFlagsImpl();
public bool IsAbstract => (GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0;
public bool IsImport => (GetAttributeFlagsImpl() & TypeAttributes.Import) != 0;
public bool IsSealed => (GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0;
public bool IsSpecialName => (GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0;
public bool IsClass => (GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class && !IsValueType;
public bool IsNestedAssembly => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly;
public bool IsNestedFamANDAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem;
public bool IsNestedFamily => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily;
public bool IsNestedFamORAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamORAssem;
public bool IsNestedPrivate => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate;
public bool IsNestedPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic;
public bool IsNotPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NotPublic;
public bool IsPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public;
public bool IsAutoLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.AutoLayout;
public bool IsExplicitLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout;
public bool IsLayoutSequential => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout;
public bool IsAnsiClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AnsiClass;
public bool IsAutoClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass;
public bool IsUnicodeClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass;
public bool IsCOMObject => IsCOMObjectImpl();
protected abstract bool IsCOMObjectImpl();
public bool IsContextful => IsContextfulImpl();
protected virtual bool IsContextfulImpl() => false;
public virtual bool IsEnum => IsSubclassOf(typeof(Enum));
public bool IsMarshalByRef => IsMarshalByRefImpl();
protected virtual bool IsMarshalByRefImpl() => false;
public bool IsPrimitive => IsPrimitiveImpl();
protected abstract bool IsPrimitiveImpl();
public bool IsValueType => IsValueTypeImpl();
protected virtual bool IsValueTypeImpl() => IsSubclassOf(typeof(ValueType));
public virtual bool IsSignatureType => false;
public virtual bool IsSecurityCritical => throw NotImplemented.ByDesign;
public virtual bool IsSecuritySafeCritical => throw NotImplemented.ByDesign;
public virtual bool IsSecurityTransparent => throw NotImplemented.ByDesign;
public virtual StructLayoutAttribute? StructLayoutAttribute => throw new NotSupportedException();
public ConstructorInfo? TypeInitializer => GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, Type.EmptyTypes, null);
public ConstructorInfo? GetConstructor(Type[] types) => GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, types, null);
public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers);
public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers);
public ConstructorInfo[] GetConstructors() => GetConstructors(BindingFlags.Public | BindingFlags.Instance);
public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr);
public EventInfo? GetEvent(string name) => GetEvent(name, Type.DefaultLookup);
public abstract EventInfo? GetEvent(string name, BindingFlags bindingAttr);
public virtual EventInfo[] GetEvents() => GetEvents(Type.DefaultLookup);
public abstract EventInfo[] GetEvents(BindingFlags bindingAttr);
public FieldInfo? GetField(string name) => GetField(name, Type.DefaultLookup);
public abstract FieldInfo? GetField(string name, BindingFlags bindingAttr);
public FieldInfo[] GetFields() => GetFields(Type.DefaultLookup);
public abstract FieldInfo[] GetFields(BindingFlags bindingAttr);
public MemberInfo[] GetMember(string name) => GetMember(name, Type.DefaultLookup);
public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr) => GetMember(name, MemberTypes.All, bindingAttr);
public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public MemberInfo[] GetMembers() => GetMembers(Type.DefaultLookup);
public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr);
public MethodInfo? GetMethod(string name) => GetMethod(name, Type.DefaultLookup);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null);
}
public MethodInfo? GetMethod(string name, Type[] types) => GetMethod(name, types, null);
public MethodInfo? GetMethod(string name, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, Type.DefaultLookup, null, types, modifiers);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers);
public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers);
}
protected abstract MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types) => GetMethod(name, genericParameterCount, types, null);
public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, Type.DefaultLookup, null, types, modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers);
public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (genericParameterCount < 0)
throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount));
if (types == null)
throw new ArgumentNullException(nameof(types));
for (int i = 0; i < types.Length; i++)
{
if (types[i] == null)
throw new ArgumentNullException(nameof(types));
}
return GetMethodImpl(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers);
}
protected virtual MethodInfo? GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) => throw new NotSupportedException();
public MethodInfo[] GetMethods() => GetMethods(Type.DefaultLookup);
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr);
public Type? GetNestedType(string name) => GetNestedType(name, Type.DefaultLookup);
public abstract Type? GetNestedType(string name, BindingFlags bindingAttr);
public Type[] GetNestedTypes() => GetNestedTypes(Type.DefaultLookup);
public abstract Type[] GetNestedTypes(BindingFlags bindingAttr);
public PropertyInfo? GetProperty(string name) => GetProperty(name, Type.DefaultLookup);
public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetPropertyImpl(name, bindingAttr, null, null, null, null);
}
public PropertyInfo? GetProperty(string name, Type? returnType)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
return GetPropertyImpl(name, Type.DefaultLookup, null, returnType, null, null);
}
public PropertyInfo? GetProperty(string name, Type[] types) => GetProperty(name, null, types);
public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types) => GetProperty(name, returnType, types, null);
public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types, ParameterModifier[]? modifiers) => GetProperty(name, Type.DefaultLookup, null, returnType, types, modifiers);
public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
if (types == null)
throw new ArgumentNullException(nameof(types));
return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers);
}
protected abstract PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers);
public PropertyInfo[] GetProperties() => GetProperties(Type.DefaultLookup);
public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr);
public virtual MemberInfo[] GetDefaultMembers() => throw NotImplemented.ByDesign;
public virtual RuntimeTypeHandle TypeHandle => throw new NotSupportedException();
public static RuntimeTypeHandle GetTypeHandle(object o)
{
if (o == null)
throw new ArgumentNullException(null, SR.Arg_InvalidHandle);
Type type = o.GetType();
return type.TypeHandle;
}
public static Type[] GetTypeArray(object[] args)
{
if (args == null)
throw new ArgumentNullException(nameof(args));
Type[] cls = new Type[args.Length];
for (int i = 0; i < cls.Length; i++)
{
if (args[i] == null)
throw new ArgumentNullException();
cls[i] = args[i].GetType();
}
return cls;
}
public static TypeCode GetTypeCode(Type? type)
{
if (type == null)
return TypeCode.Empty;
return type.GetTypeCodeImpl();
}
protected virtual TypeCode GetTypeCodeImpl()
{
Type systemType = UnderlyingSystemType;
if (this != systemType && systemType != null)
return Type.GetTypeCode(systemType);
return TypeCode.Object;
}
public abstract Guid GUID { get; }
public static Type? GetTypeFromCLSID(Guid clsid) => GetTypeFromCLSID(clsid, null, throwOnError: false);
public static Type? GetTypeFromCLSID(Guid clsid, bool throwOnError) => GetTypeFromCLSID(clsid, null, throwOnError: throwOnError);
public static Type? GetTypeFromCLSID(Guid clsid, string? server) => GetTypeFromCLSID(clsid, server, throwOnError: false);
public static Type? GetTypeFromProgID(string progID) => GetTypeFromProgID(progID, null, throwOnError: false);
public static Type? GetTypeFromProgID(string progID, bool throwOnError) => GetTypeFromProgID(progID, null, throwOnError: throwOnError);
public static Type? GetTypeFromProgID(string progID, string? server) => GetTypeFromProgID(progID, server, throwOnError: false);
public abstract Type? BaseType { get; }
[DebuggerHidden]
[DebuggerStepThrough]
public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args) => InvokeMember(name, invokeAttr, binder, target, args, null, null, null);
[DebuggerHidden]
[DebuggerStepThrough]
public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, CultureInfo? culture) => InvokeMember(name, invokeAttr, binder, target, args, null, culture, null);
public abstract object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters);
public Type? GetInterface(string name) => GetInterface(name, ignoreCase: false);
public abstract Type? GetInterface(string name, bool ignoreCase);
public abstract Type[] GetInterfaces();
public virtual InterfaceMapping GetInterfaceMap(Type interfaceType) => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public virtual bool IsInstanceOfType(object? o) => o == null ? false : IsAssignableFrom(o.GetType());
public virtual bool IsEquivalentTo(Type? other) => this == other;
public virtual Type GetEnumUnderlyingType()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
FieldInfo[] fields = GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
if (fields == null || fields.Length != 1)
throw new ArgumentException(SR.Argument_InvalidEnum, "enumType");
return fields[0].FieldType;
}
public virtual Array GetEnumValues()
{
if (!IsEnum)
throw new ArgumentException(SR.Arg_MustBeEnum, "enumType");
// We don't support GetEnumValues in the default implementation because we cannot create an array of
// a non-runtime type. If there is strong need we can consider returning an object or int64 array.
throw NotImplemented.ByDesign;
}
public virtual Type MakeArrayType() => throw new NotSupportedException();
public virtual Type MakeArrayType(int rank) => throw new NotSupportedException();
public virtual Type MakeByRefType() => throw new NotSupportedException();
public virtual Type MakeGenericType(params Type[] typeArguments) => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
public virtual Type MakePointerType() => throw new NotSupportedException();
public static Type MakeGenericSignatureType(Type genericTypeDefinition, params Type[] typeArguments) => new SignatureConstructedGenericType(genericTypeDefinition, typeArguments);
public static Type MakeGenericMethodParameter(int position)
{
if (position < 0)
throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(position));
return new SignatureGenericMethodParameterType(position);
}
// This is used by the ToString() overrides of all reflection types. The legacy behavior has the following problems:
// 1. Use only Name for nested types, which can be confused with global types and generic parameters of the same name.
// 2. Use only Name for generic parameters, which can be confused with nested types and global types of the same name.
// 3. Use only Name for all primitive types, void and TypedReference
// 4. MethodBase.ToString() use "ByRef" for byref parameters which is different than Type.ToString().
// 5. ConstructorInfo.ToString() outputs "Void" as the return type. Why Void?
internal string FormatTypeName()
{
Type elementType = GetRootElementType();
if (elementType.IsPrimitive ||
elementType.IsNested ||
elementType == typeof(void) ||
elementType == typeof(TypedReference))
return Name;
return ToString();
}
public override string ToString() => "Type: " + Name; // Why do we add the "Type: " prefix?
public override bool Equals(object? o) => o == null ? false : Equals(o as Type);
public override int GetHashCode()
{
Type systemType = UnderlyingSystemType;
if (!object.ReferenceEquals(systemType, this))
return systemType.GetHashCode();
return base.GetHashCode();
}
public virtual bool Equals(Type? o) => o == null ? false : object.ReferenceEquals(this.UnderlyingSystemType, o.UnderlyingSystemType);
public static Type? ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) => throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly);
public static Binder DefaultBinder
{
get
{
if (s_defaultBinder == null)
{
DefaultBinder binder = new DefaultBinder();
Interlocked.CompareExchange<Binder?>(ref s_defaultBinder, binder, null);
}
return s_defaultBinder!;
}
}
private static volatile Binder? s_defaultBinder;
public static readonly char Delimiter = '.';
public static readonly Type[] EmptyTypes = Array.Empty<Type>();
public static readonly object Missing = System.Reflection.Missing.Value;
public static readonly MemberFilter FilterAttribute = FilterAttributeImpl!;
public static readonly MemberFilter FilterName = (m, c) => FilterNameImpl(m, c!, StringComparison.Ordinal);
public static readonly MemberFilter FilterNameIgnoreCase = (m, c) => FilterNameImpl(m, c!, StringComparison.OrdinalIgnoreCase);
private const BindingFlags DefaultLookup = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
}
}
| |
using NLog;
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace Lewis.SST.AsyncMethods
{
/// <summary>
/// Summary description for AsyncUtils.
/// Class taken from article on Codeproject.com, http://www.codeproject.com/csharp/LaunchProcess.asp
/// </summary>
/// <summary>
/// Exception thrown by AsyncUtils.AsyncOperation.Start when an
/// operation is already in progress.
/// </summary>
public class AlreadyRunningException : System.ApplicationException
{
/// <summary>
/// The single method for the AlreadyRunningException class throws an exception using the base inherited class: System.ApplicationException.
/// </summary>
public AlreadyRunningException() : base("Asynchronous operation already running")
{ }
}
/// <summary>
/// The abstract class for AsyncOperation
/// </summary>
public abstract class AsyncOperation
{
private static Logger logger = LogManager.GetLogger("Lewis.SST.AsyncMethods.AsyncOperation");
/// <summary>
/// Initialises an AsyncOperation with an association to the
/// supplied ISynchronizeInvoke. All events raised from this
/// object will be delivered via this target. (This might be a
/// Control object, so events would be delivered to that Control's
/// UI thread.)
/// </summary>
/// <param name="target">An object implementing the
/// ISynchronizeInvoke interface. All events will be delivered
/// through this target, ensuring that they are delivered to the
/// correct thread.</param>
public AsyncOperation(ISynchronizeInvoke target)
{
isiTarget = target;
isRunning = false;
}
/// <summary>
/// Launch the operation on a worker thread. This method will
/// return immediately, and the operation will start asynchronously
/// on a worker thread.
/// </summary>
public void Start()
{
lock(this)
{
if (isRunning)
{
throw new AlreadyRunningException();
}
// Set this flag here, not inside InternalStart, to avoid
// race condition when Start called twice in quick
// succession.
isRunning = true;
}
new MethodInvoker(InternalStart).BeginInvoke(null, null);
}
/// <summary>
/// Attempt to cancel the current operation. This returns
/// immediately to the caller. No guarantee is made as to
/// whether the operation will be successfully cancelled. All
/// that can be known is that at some point, one of the
/// three events Completed, Cancelled, or Failed will be raised
/// at some point.
/// </summary>
public void Cancel()
{
lock(this)
{
cancelledFlag = true;
}
}
/// <summary>
/// Attempt to cancel the current operation and block until either
/// the cancellation succeeds or the operation completes.
/// </summary>
/// <returns>true if the operation was successfully cancelled
/// or it failed, false if it ran to completion.</returns>
public bool CancelAndWait()
{
lock(this)
{
// Set the cancelled flag
cancelledFlag = true;
// Now sit and wait either for the operation to
// complete or the cancellation to be acknowledged.
// (Wake up and check every second - shouldn't be
// necessary, but it guarantees we won't deadlock
// if for some reason the Pulse gets lost - means
// we don't have to worry so much about bizarre
// race conditions.)
while(!IsDone)
{
Monitor.Wait(this, 1000);
}
}
return !HasCompleted;
}
/// <summary>
/// Blocks until the operation has either run to completion, or has
/// been successfully cancelled, or has failed with an internal
/// exception.
/// </summary>
/// <returns>true if the operation completed, false if it was
/// cancelled before completion or failed with an internal
/// exception.</returns>
public bool WaitUntilDone()
{
lock(this)
{
// Wait for either completion or cancellation. As with
// CancelAndWait, we don't sleep forever - to reduce the
// chances of deadlock in obscure race conditions, we wake
// up every second to check we didn't miss a Pulse.
while (!IsDone)
{
Monitor.Wait(this, 1000);
}
}
return HasCompleted;
}
/// <summary>
/// Returns false if the operation is still in progress, or true if
/// it has either completed successfully, been cancelled
/// successfully, or failed with an internal exception.
/// </summary>
public bool IsDone
{
get
{
lock(this)
{
return completeFlag || cancelAcknowledgedFlag || failedFlag;
}
}
}
/// <summary>
/// This event will be fired if the operation runs to completion
/// without being cancelled. This event will be raised through the
/// ISynchronizeTarget supplied at construction time. Note that
/// this event may still be received after a cancellation request
/// has been issued. (This would happen if the operation completed
/// at about the same time that cancellation was requested.) But
/// the event is not raised if the operation is cancelled
/// successfully.
/// </summary>
public event EventHandler Completed;
/// <summary>
/// This event will be fired when the operation is successfully
/// stoped through cancellation. This event will be raised through
/// the ISynchronizeTarget supplied at construction time.
/// </summary>
public event EventHandler Cancelled;
/// <summary>
/// This event will be fired if the operation throws an exception.
/// This event will be raised through the ISynchronizeTarget
/// supplied at construction time.
/// </summary>
public event System.Threading.ThreadExceptionEventHandler Failed;
/// <summary>
/// The ISynchronizeTarget supplied during construction - this can
/// be used by deriving classes which wish to add their own events.
/// </summary>
protected ISynchronizeInvoke Target
{
get { return isiTarget; }
}
private ISynchronizeInvoke isiTarget;
/// <summary>
/// To be overridden by the deriving class - this is where the work
/// will be done. The base class calls this method on a worker
/// thread when the Start method is called.
/// </summary>
protected abstract void DoWork();
/// <summary>
/// Flag indicating whether the request has been cancelled. Long-
/// running operations should check this flag regularly if they can
/// and cancel their operations as soon as they notice that it has
/// been set.
/// </summary>
protected bool CancelRequested
{
get
{
lock(this) { return cancelledFlag; }
}
}
private bool cancelledFlag;
/// <summary>
/// Flag indicating whether the request has run through to
/// completion. This will be false if the request has been
/// successfully cancelled, or if it failed.
/// </summary>
protected bool HasCompleted
{
get
{
lock(this) { return completeFlag; }
}
}
private bool completeFlag;
/// <summary>
/// This is called by the operation when it wants to indicate that
/// it saw the cancellation request and honoured it.
/// </summary>
protected void AcknowledgeCancel()
{
lock(this)
{
cancelAcknowledgedFlag = true;
isRunning = false;
// Pulse the event in case the main thread is blocked
// waiting for us to finish (e.g. in CancelAndWait or
// WaitUntilDone).
Monitor.Pulse(this);
// Using async invocation to avoid a potential deadlock
// - using Invoke would involve a cross-thread call
// whilst we still held the object lock. If the event
// handler on the UI thread tries to access this object
// it will block because we have the lock, but using
// async invocation here means that once we've fired
// the event, we'll run on and release the object lock,
// unblocking the UI thread.
FireAsync(Cancelled, this, EventArgs.Empty);
}
}
private bool cancelAcknowledgedFlag;
///<summary>
/// Set to true if the operation fails with an exception.
///</summary>
private bool failedFlag;
///<summary>
/// Set to true if the operation is running
///</summary>
private bool isRunning;
/// <summary>
/// This method is called on a worker thread (via asynchronous
/// delegate invocation). This is where we call the operation (as
/// defined in the deriving class's DoWork method).
/// </summary>
private void InternalStart()
{
// Reset our state - we might be run more than once.
cancelledFlag = false;
completeFlag = false;
cancelAcknowledgedFlag = false;
failedFlag = false;
// isRunning is set during Start to avoid a race condition
try
{
DoWork();
}
catch (Exception e)
{
// Raise the Failed event. We're in a catch handler, so we
// had better try not to throw another exception.
try
{
FailOperation(e);
}
catch
{ }
// The documentation recommends not catching
// SystemExceptions, so having notified the caller we
// rethrow if it was one of them.
if (e is SystemException)
{
logger.Error(SQLSchemaTool.ERRORFORMAT, e.Message, e.Source, e.StackTrace);
}
}
lock(this)
{
// If the operation wasn't cancelled (or if the UI thread
// tried to cancel it, but the method ran to completion
// anyway before noticing the cancellation) and it
// didn't fail with an exception, then we complete the
// operation - if the UI thread was blocked waiting for
// cancellation to complete it will be unblocked, and
// the Completion event will be raised.
if (!cancelAcknowledgedFlag && !failedFlag)
{
CompleteOperation();
}
}
}
/// <summary>
/// This is called when the operation runs to completion.
/// (This is private because it is called automatically
/// by this base class when the deriving class's DoWork
/// method exits without having cancelled
/// </summary>
private void CompleteOperation()
{
lock(this)
{
completeFlag = true;
isRunning = false;
Monitor.Pulse(this);
// See comments in AcknowledgeCancel re use of
// Async.
FireAsync(Completed, this, EventArgs.Empty);
}
}
/// <summary>
/// Fires event when the operation fails.
/// </summary>
/// <param name="e">The exception.</param>
private void FailOperation(Exception e)
{
lock(this)
{
failedFlag = true;
isRunning = false;
Monitor.Pulse(this);
FireAsync(Failed, this, new ThreadExceptionEventArgs(e));
}
}
/// <summary>
/// Utility function for firing an event through the target.
/// It uses C#'s variable length parameter list support
/// to build the parameter list.
///
/// This functions presumes that the caller holds the object lock.
/// (This is because the event list is typically modified on the UI
/// thread, but events are usually raised on the worker thread.)
/// </summary>
/// <param name="dlg">The async thread Delegate.</param>
/// <param name="pList">The param list array.</param>
protected void FireAsync(Delegate dlg, params object[] pList)
{
if (dlg != null)
{
try
{
Target.BeginInvoke(dlg, pList);
}
catch (Exception ex)
{
logger.Error(SQLSchemaTool.ERRORFORMAT, ex.Message, ex.Source, ex.StackTrace);
}
}
}
}
}
| |
namespace Epi.Windows.Analysis.Dialogs
{
partial class KaplanMeierSurvivalDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(KaplanMeierSurvivalDialog));
this.cmbWeightVar = new System.Windows.Forms.ComboBox();
this.lblWeight = new System.Windows.Forms.Label();
this.lblOutput = new System.Windows.Forms.Label();
this.txtOutput = new System.Windows.Forms.TextBox();
this.cmbCensoredVar = new System.Windows.Forms.ComboBox();
this.lblCensoredVar = new System.Windows.Forms.Label();
this.lbxOther = new System.Windows.Forms.ListBox();
this.btnHelp = new System.Windows.Forms.Button();
this.btnClear = new System.Windows.Forms.Button();
this.btnOK = new System.Windows.Forms.Button();
this.btnSaveOnly = new System.Windows.Forms.Button();
this.cmbOther = new System.Windows.Forms.ComboBox();
this.lblOther = new System.Windows.Forms.Label();
this.cmbConfLimits = new System.Windows.Forms.ComboBox();
this.lblConfLimits = new System.Windows.Forms.Label();
this.btnModifyTerm = new System.Windows.Forms.Button();
this.lblDummyVar = new System.Windows.Forms.Label();
this.lblInteractionTerms = new System.Windows.Forms.Label();
this.lbxInteractionTerms = new System.Windows.Forms.ListBox();
this.btnCancel = new System.Windows.Forms.Button();
this.cmbUncensoredValue = new System.Windows.Forms.ComboBox();
this.lblUncensoredValue = new System.Windows.Forms.Label();
this.cmbTimeVar = new System.Windows.Forms.ComboBox();
this.lblTimeVar = new System.Windows.Forms.Label();
this.cmbGroupVar = new System.Windows.Forms.ComboBox();
this.lblGroupVar = new System.Windows.Forms.Label();
this.cmbTimeUnit = new System.Windows.Forms.ComboBox();
this.lblTimeUnit = new System.Windows.Forms.Label();
this.cmbStrataVar = new System.Windows.Forms.ComboBox();
this.lblStrataVars = new System.Windows.Forms.Label();
this.btnMakeExtended = new System.Windows.Forms.Button();
this.lbxExtendedTerms = new System.Windows.Forms.ListBox();
this.lbxStrataVars = new System.Windows.Forms.ListBox();
this.lblExtendedTerms = new System.Windows.Forms.Label();
this.grpGraphOpts = new System.Windows.Forms.GroupBox();
this.chkCustomGraph = new System.Windows.Forms.CheckBox();
this.lbxGraphVars = new System.Windows.Forms.ListBox();
this.lblPlotVariables = new System.Windows.Forms.Label();
this.cmbGraphType = new System.Windows.Forms.ComboBox();
this.lblGraphType = new System.Windows.Forms.Label();
this.grpGraphOpts.SuspendLayout();
this.SuspendLayout();
//
// baseImageList
//
this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream")));
this.baseImageList.Images.SetKeyName(0, "");
this.baseImageList.Images.SetKeyName(1, "");
this.baseImageList.Images.SetKeyName(2, "");
this.baseImageList.Images.SetKeyName(3, "");
this.baseImageList.Images.SetKeyName(4, "");
this.baseImageList.Images.SetKeyName(5, "");
this.baseImageList.Images.SetKeyName(6, "");
this.baseImageList.Images.SetKeyName(7, "");
this.baseImageList.Images.SetKeyName(8, "");
this.baseImageList.Images.SetKeyName(9, "");
this.baseImageList.Images.SetKeyName(10, "");
this.baseImageList.Images.SetKeyName(11, "");
this.baseImageList.Images.SetKeyName(12, "");
this.baseImageList.Images.SetKeyName(13, "");
this.baseImageList.Images.SetKeyName(14, "");
this.baseImageList.Images.SetKeyName(15, "");
this.baseImageList.Images.SetKeyName(16, "");
this.baseImageList.Images.SetKeyName(17, "");
this.baseImageList.Images.SetKeyName(18, "");
this.baseImageList.Images.SetKeyName(19, "");
this.baseImageList.Images.SetKeyName(20, "");
this.baseImageList.Images.SetKeyName(21, "");
this.baseImageList.Images.SetKeyName(22, "");
this.baseImageList.Images.SetKeyName(23, "");
this.baseImageList.Images.SetKeyName(24, "");
this.baseImageList.Images.SetKeyName(25, "");
this.baseImageList.Images.SetKeyName(26, "");
this.baseImageList.Images.SetKeyName(27, "");
this.baseImageList.Images.SetKeyName(28, "");
this.baseImageList.Images.SetKeyName(29, "");
this.baseImageList.Images.SetKeyName(30, "");
this.baseImageList.Images.SetKeyName(31, "");
this.baseImageList.Images.SetKeyName(32, "");
this.baseImageList.Images.SetKeyName(33, "");
this.baseImageList.Images.SetKeyName(34, "");
this.baseImageList.Images.SetKeyName(35, "");
this.baseImageList.Images.SetKeyName(36, "");
this.baseImageList.Images.SetKeyName(37, "");
this.baseImageList.Images.SetKeyName(38, "");
this.baseImageList.Images.SetKeyName(39, "");
this.baseImageList.Images.SetKeyName(40, "");
this.baseImageList.Images.SetKeyName(41, "");
this.baseImageList.Images.SetKeyName(42, "");
this.baseImageList.Images.SetKeyName(43, "");
this.baseImageList.Images.SetKeyName(44, "");
this.baseImageList.Images.SetKeyName(45, "");
this.baseImageList.Images.SetKeyName(46, "");
this.baseImageList.Images.SetKeyName(47, "");
this.baseImageList.Images.SetKeyName(48, "");
this.baseImageList.Images.SetKeyName(49, "");
this.baseImageList.Images.SetKeyName(50, "");
this.baseImageList.Images.SetKeyName(51, "");
this.baseImageList.Images.SetKeyName(52, "");
this.baseImageList.Images.SetKeyName(53, "");
this.baseImageList.Images.SetKeyName(54, "");
this.baseImageList.Images.SetKeyName(55, "");
this.baseImageList.Images.SetKeyName(56, "");
this.baseImageList.Images.SetKeyName(57, "");
this.baseImageList.Images.SetKeyName(58, "");
this.baseImageList.Images.SetKeyName(59, "");
this.baseImageList.Images.SetKeyName(60, "");
this.baseImageList.Images.SetKeyName(61, "");
this.baseImageList.Images.SetKeyName(62, "");
this.baseImageList.Images.SetKeyName(63, "");
this.baseImageList.Images.SetKeyName(64, "");
this.baseImageList.Images.SetKeyName(65, "");
this.baseImageList.Images.SetKeyName(66, "");
this.baseImageList.Images.SetKeyName(67, "");
this.baseImageList.Images.SetKeyName(68, "");
this.baseImageList.Images.SetKeyName(69, "");
this.baseImageList.Images.SetKeyName(70, "");
this.baseImageList.Images.SetKeyName(71, "");
this.baseImageList.Images.SetKeyName(72, "");
this.baseImageList.Images.SetKeyName(73, "");
this.baseImageList.Images.SetKeyName(74, "");
this.baseImageList.Images.SetKeyName(75, "");
//
// cmbWeightVar
//
this.cmbWeightVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbWeightVar, "cmbWeightVar");
this.cmbWeightVar.Name = "cmbWeightVar";
this.cmbWeightVar.SelectedIndexChanged += new System.EventHandler(this.cmbWeightVar_SelectedIndexChanged);
this.cmbWeightVar.Click += new System.EventHandler(this.cmbWeightVar_Click);
this.cmbWeightVar.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbWeightVar_KeyDown);
//
// lblWeight
//
resources.ApplyResources(this.lblWeight, "lblWeight");
this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblWeight.Name = "lblWeight";
//
// lblOutput
//
resources.ApplyResources(this.lblOutput, "lblOutput");
this.lblOutput.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblOutput.Name = "lblOutput";
//
// txtOutput
//
resources.ApplyResources(this.txtOutput, "txtOutput");
this.txtOutput.Name = "txtOutput";
//
// cmbCensoredVar
//
this.cmbCensoredVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbCensoredVar, "cmbCensoredVar");
this.cmbCensoredVar.Name = "cmbCensoredVar";
this.cmbCensoredVar.SelectedIndexChanged += new System.EventHandler(this.cmbCensoredVar_SelectedIndexChanged);
this.cmbCensoredVar.Click += new System.EventHandler(this.cmbCensoredVar_Click);
//
// lblCensoredVar
//
resources.ApplyResources(this.lblCensoredVar, "lblCensoredVar");
this.lblCensoredVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblCensoredVar.Name = "lblCensoredVar";
//
// lbxOther
//
resources.ApplyResources(this.lbxOther, "lbxOther");
this.lbxOther.Name = "lbxOther";
this.lbxOther.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.lbxOther.SelectedIndexChanged += new System.EventHandler(this.lbxOther_SelectedIndexChanged);
this.lbxOther.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxOther_KeyDown);
//
// btnHelp
//
resources.ApplyResources(this.btnHelp, "btnHelp");
this.btnHelp.Name = "btnHelp";
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// btnClear
//
resources.ApplyResources(this.btnClear, "btnClear");
this.btnClear.Name = "btnClear";
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
//
// btnOK
//
resources.ApplyResources(this.btnOK, "btnOK");
this.btnOK.Name = "btnOK";
//
// btnSaveOnly
//
resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly");
this.btnSaveOnly.Name = "btnSaveOnly";
//
// cmbOther
//
this.cmbOther.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbOther, "cmbOther");
this.cmbOther.Name = "cmbOther";
this.cmbOther.SelectedIndexChanged += new System.EventHandler(this.cmbOther_SelectedIndexChanged);
this.cmbOther.Click += new System.EventHandler(this.cmbOther_Click);
//
// lblOther
//
resources.ApplyResources(this.lblOther, "lblOther");
this.lblOther.BackColor = System.Drawing.Color.Transparent;
this.lblOther.Name = "lblOther";
//
// cmbConfLimits
//
this.cmbConfLimits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbConfLimits, "cmbConfLimits");
this.cmbConfLimits.Items.AddRange(new object[] {
resources.GetString("cmbConfLimits.Items"),
resources.GetString("cmbConfLimits.Items1"),
resources.GetString("cmbConfLimits.Items2"),
resources.GetString("cmbConfLimits.Items3")});
this.cmbConfLimits.Name = "cmbConfLimits";
//
// lblConfLimits
//
resources.ApplyResources(this.lblConfLimits, "lblConfLimits");
this.lblConfLimits.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblConfLimits.Name = "lblConfLimits";
//
// btnModifyTerm
//
resources.ApplyResources(this.btnModifyTerm, "btnModifyTerm");
this.btnModifyTerm.Name = "btnModifyTerm";
this.btnModifyTerm.Click += new System.EventHandler(this.btnModifyTerm_Click);
//
// lblDummyVar
//
resources.ApplyResources(this.lblDummyVar, "lblDummyVar");
this.lblDummyVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblDummyVar.Name = "lblDummyVar";
//
// lblInteractionTerms
//
resources.ApplyResources(this.lblInteractionTerms, "lblInteractionTerms");
this.lblInteractionTerms.Name = "lblInteractionTerms";
//
// lbxInteractionTerms
//
resources.ApplyResources(this.lbxInteractionTerms, "lbxInteractionTerms");
this.lbxInteractionTerms.Name = "lbxInteractionTerms";
this.lbxInteractionTerms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxInteractionTerms_KeyDown);
//
// btnCancel
//
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.btnCancel, "btnCancel");
this.btnCancel.Name = "btnCancel";
//
// cmbUncensoredValue
//
this.cmbUncensoredValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbUncensoredValue, "cmbUncensoredValue");
this.cmbUncensoredValue.Name = "cmbUncensoredValue";
this.cmbUncensoredValue.SelectedIndexChanged += new System.EventHandler(this.cmbUncensoredValue_SelectedIndexChanged);
//
// lblUncensoredValue
//
resources.ApplyResources(this.lblUncensoredValue, "lblUncensoredValue");
this.lblUncensoredValue.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblUncensoredValue.Name = "lblUncensoredValue";
//
// cmbTimeVar
//
this.cmbTimeVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbTimeVar, "cmbTimeVar");
this.cmbTimeVar.Name = "cmbTimeVar";
this.cmbTimeVar.SelectedIndexChanged += new System.EventHandler(this.cmbTimeVar_SelectedIndexChanged);
this.cmbTimeVar.Click += new System.EventHandler(this.cmbTimeVar_Click);
//
// lblTimeVar
//
resources.ApplyResources(this.lblTimeVar, "lblTimeVar");
this.lblTimeVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblTimeVar.Name = "lblTimeVar";
//
// cmbGroupVar
//
this.cmbGroupVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbGroupVar, "cmbGroupVar");
this.cmbGroupVar.Name = "cmbGroupVar";
this.cmbGroupVar.SelectedIndexChanged += new System.EventHandler(this.cmbGroupVar_SelectedIndexChanged);
this.cmbGroupVar.Click += new System.EventHandler(this.cmbGroupVar_Click);
//
// lblGroupVar
//
resources.ApplyResources(this.lblGroupVar, "lblGroupVar");
this.lblGroupVar.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblGroupVar.Name = "lblGroupVar";
//
// cmbTimeUnit
//
this.cmbTimeUnit.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbTimeUnit, "cmbTimeUnit");
this.cmbTimeUnit.Name = "cmbTimeUnit";
//
// lblTimeUnit
//
resources.ApplyResources(this.lblTimeUnit, "lblTimeUnit");
this.lblTimeUnit.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblTimeUnit.Name = "lblTimeUnit";
//
// cmbStrataVar
//
this.cmbStrataVar.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbStrataVar, "cmbStrataVar");
this.cmbStrataVar.Name = "cmbStrataVar";
this.cmbStrataVar.SelectedIndexChanged += new System.EventHandler(this.cmbStrataVar_SelectedIndexChanged);
this.cmbStrataVar.Click += new System.EventHandler(this.cmbStrataVar_Click);
//
// lblStrataVars
//
resources.ApplyResources(this.lblStrataVars, "lblStrataVars");
this.lblStrataVars.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblStrataVars.Name = "lblStrataVars";
//
// btnMakeExtended
//
resources.ApplyResources(this.btnMakeExtended, "btnMakeExtended");
this.btnMakeExtended.Name = "btnMakeExtended";
//
// lbxExtendedTerms
//
resources.ApplyResources(this.lbxExtendedTerms, "lbxExtendedTerms");
this.lbxExtendedTerms.Name = "lbxExtendedTerms";
this.lbxExtendedTerms.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
this.lbxExtendedTerms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxExtendedTerms_KeyDown);
//
// lbxStrataVars
//
resources.ApplyResources(this.lbxStrataVars, "lbxStrataVars");
this.lbxStrataVars.Name = "lbxStrataVars";
this.lbxStrataVars.KeyDown += new System.Windows.Forms.KeyEventHandler(this.lbxStrataVars_KeyDown);
//
// lblExtendedTerms
//
resources.ApplyResources(this.lblExtendedTerms, "lblExtendedTerms");
this.lblExtendedTerms.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblExtendedTerms.Name = "lblExtendedTerms";
//
// grpGraphOpts
//
this.grpGraphOpts.Controls.Add(this.chkCustomGraph);
this.grpGraphOpts.Controls.Add(this.lbxGraphVars);
this.grpGraphOpts.Controls.Add(this.lblPlotVariables);
resources.ApplyResources(this.grpGraphOpts, "grpGraphOpts");
this.grpGraphOpts.Name = "grpGraphOpts";
this.grpGraphOpts.TabStop = false;
//
// chkCustomGraph
//
resources.ApplyResources(this.chkCustomGraph, "chkCustomGraph");
this.chkCustomGraph.Checked = true;
this.chkCustomGraph.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCustomGraph.Name = "chkCustomGraph";
this.chkCustomGraph.UseVisualStyleBackColor = true;
//
// lbxGraphVars
//
resources.ApplyResources(this.lbxGraphVars, "lbxGraphVars");
this.lbxGraphVars.Name = "lbxGraphVars";
this.lbxGraphVars.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;
//
// lblPlotVariables
//
resources.ApplyResources(this.lblPlotVariables, "lblPlotVariables");
this.lblPlotVariables.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblPlotVariables.Name = "lblPlotVariables";
//
// cmbGraphType
//
this.cmbGraphType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
resources.ApplyResources(this.cmbGraphType, "cmbGraphType");
this.cmbGraphType.Name = "cmbGraphType";
//
// lblGraphType
//
resources.ApplyResources(this.lblGraphType, "lblGraphType");
this.lblGraphType.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.lblGraphType.Name = "lblGraphType";
//
// KaplanMeierSurvivalDialog
//
this.AcceptButton = this.btnOK;
resources.ApplyResources(this, "$this");
this.CancelButton = this.btnCancel;
this.Controls.Add(this.lblGraphType);
this.Controls.Add(this.grpGraphOpts);
this.Controls.Add(this.lblExtendedTerms);
this.Controls.Add(this.cmbGraphType);
this.Controls.Add(this.lbxStrataVars);
this.Controls.Add(this.lbxExtendedTerms);
this.Controls.Add(this.btnMakeExtended);
this.Controls.Add(this.cmbStrataVar);
this.Controls.Add(this.lblStrataVars);
this.Controls.Add(this.cmbTimeUnit);
this.Controls.Add(this.lblTimeUnit);
this.Controls.Add(this.cmbGroupVar);
this.Controls.Add(this.lblGroupVar);
this.Controls.Add(this.cmbTimeVar);
this.Controls.Add(this.lblTimeVar);
this.Controls.Add(this.cmbUncensoredValue);
this.Controls.Add(this.lblUncensoredValue);
this.Controls.Add(this.lbxInteractionTerms);
this.Controls.Add(this.lblInteractionTerms);
this.Controls.Add(this.lblDummyVar);
this.Controls.Add(this.btnModifyTerm);
this.Controls.Add(this.cmbConfLimits);
this.Controls.Add(this.lblConfLimits);
this.Controls.Add(this.cmbOther);
this.Controls.Add(this.btnSaveOnly);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.lbxOther);
this.Controls.Add(this.cmbCensoredVar);
this.Controls.Add(this.lblCensoredVar);
this.Controls.Add(this.lblOutput);
this.Controls.Add(this.txtOutput);
this.Controls.Add(this.cmbWeightVar);
this.Controls.Add(this.lblWeight);
this.Controls.Add(this.lblOther);
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "KaplanMeierSurvivalDialog";
this.ShowIcon = false;
this.Load += new System.EventHandler(this.KaplanMeierSurvivalDialog_Load);
this.grpGraphOpts.ResumeLayout(false);
this.grpGraphOpts.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ComboBox cmbWeightVar;
private System.Windows.Forms.Label lblWeight;
private System.Windows.Forms.Label lblOutput;
private System.Windows.Forms.TextBox txtOutput;
private System.Windows.Forms.ComboBox cmbCensoredVar;
private System.Windows.Forms.Label lblCensoredVar;
private System.Windows.Forms.ListBox lbxOther;
private System.Windows.Forms.Button btnHelp;
private System.Windows.Forms.Button btnClear;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnSaveOnly;
private System.Windows.Forms.ComboBox cmbOther;
private System.Windows.Forms.Label lblOther;
private System.Windows.Forms.ComboBox cmbConfLimits;
private System.Windows.Forms.Label lblConfLimits;
private System.Windows.Forms.Button btnModifyTerm;
private System.Windows.Forms.Label lblDummyVar;
private System.Windows.Forms.Label lblInteractionTerms;
private System.Windows.Forms.ListBox lbxInteractionTerms;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.ComboBox cmbUncensoredValue;
private System.Windows.Forms.Label lblUncensoredValue;
private System.Windows.Forms.ComboBox cmbTimeVar;
private System.Windows.Forms.Label lblTimeVar;
private System.Windows.Forms.ComboBox cmbGroupVar;
private System.Windows.Forms.Label lblGroupVar;
private System.Windows.Forms.ComboBox cmbTimeUnit;
private System.Windows.Forms.Label lblTimeUnit;
private System.Windows.Forms.ComboBox cmbStrataVar;
private System.Windows.Forms.Label lblStrataVars;
private System.Windows.Forms.Button btnMakeExtended;
private System.Windows.Forms.ListBox lbxExtendedTerms;
private System.Windows.Forms.ListBox lbxStrataVars;
private System.Windows.Forms.Label lblExtendedTerms;
private System.Windows.Forms.GroupBox grpGraphOpts;
private System.Windows.Forms.ListBox lbxGraphVars;
private System.Windows.Forms.ComboBox cmbGraphType;
private System.Windows.Forms.Label lblPlotVariables;
private System.Windows.Forms.CheckBox chkCustomGraph;
private System.Windows.Forms.Label lblGraphType;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorInt16()
{
var test = new SimpleBinaryOpTest__XorInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorInt16
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector256<Int16> _clsVar1;
private static Vector256<Int16> _clsVar2;
private Vector256<Int16> _fld1;
private Vector256<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__XorInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__XorInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.Xor(
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.Xor(
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.Xor(
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr);
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr));
var result = Avx2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorInt16();
var result = Avx2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Int16> left, Vector256<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if ((short)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
namespace Platform.VirtualFileSystem.Providers
{
/// <summary>
/// Wraps an <i>INode</i> and emulated delegation to redirect operations
/// to the parent (wrapped) node (also known as the wrappee or target).
/// </summary>
/// <remarks>
/// <para>
/// Implementation redirection is performed using <c>delegation</c>.
/// Full delegation is not possible but is emulated in the following ways:
/// </para>
/// <para>
/// All <c>Resolve</c> calls to the <see cref="NodeDelegationWrapper.Resolver"/>.
/// The default <see cref="NodeDelegationWrapper.Resolver"/> delegates all
/// <c>Resolve</c> calls to
/// <see cref="NodeDelegationWrapper.Resolve(string, NodeType, AddressScope)"/>.
/// This allows subclasses of this class to simply override
/// <see cref="NodeDelegationWrapper.Resolve(string, NodeType, AddressScope)"/>
/// in order to delegate the behaviour of all the <c>Resolve</c> methods.
/// </para>
/// <para>
/// The <see cref="NodeDelegationWrapper.ToString()"/> method is override to
/// return <c>NodeDelegationWrapper.Address.Tostring()</c>. The default
/// implementaion of <see cref="NodeDelegationWrapper.Address"/> returns the
/// wrappee's <c>Address</c> so the default delegated behaviour for
/// <see cref="NodeDelegationWrapper.ToString()"/> is the same as
/// undelegated behaviour. Subclasses that override
/// <see cref="NodeDelegationWrapper.Address"/> will automatically get the correct
/// <see cref="NodeDelegationWrapper.ToString()"/> implementation based on
/// the override <see cref="NodeDelegationWrapper.Address"/>.
/// </para>
/// <para>
/// All methods intended to return the current node will not return
/// the wrappee but will return the <see cref="NodeDelegationWrapper"/>.
/// </para>
/// <para>
/// All methods (i.e. children or parent) returning new nodes (known as
/// adapter-condidate nodes) will return a node, optionally converted
/// (adapted) by the supplied
/// <see cref="NodeDelegationWrapper.NodeAdapter"/>. The default
/// <c>NodeAdapter</c> returns the node unadapted.
/// </para>
/// <para>
/// References:
/// http://javalab.cs.uni-bonn.de/research/darwin/delegation.html
/// </para>
/// </remarks>
public abstract class NodeDelegationWrapper
: NodeConsultationWrapper
{
internal class DefaultResolver
: AbstractResolver
{
private readonly INode node;
private INodeAddress parentAddress;
public DefaultResolver(NodeDelegationWrapper node)
{
this.node = node;
}
public override INode Resolve(string name, NodeType nodeType, AddressScope scope)
{
if (this.parentAddress == null)
{
if (this.node.NodeType == NodeType.File)
{
this.parentAddress = this.node.Address.Parent;
}
else
{
this.parentAddress = this.node.Address;
}
}
return this.node.FileSystem.Resolve(this.parentAddress.ResolveAddress(name).AbsolutePath, nodeType, scope);
}
}
protected virtual Converter<INode, INode> NodeAdapter { get; set; }
protected virtual INodeResolver NodeResolver { get; set; }
protected NodeDelegationWrapper(INode innerNode)
: this(innerNode, null, ConverterUtils<INode, INode>.NoConvert)
{
}
/// <summary>
/// Construct a new <see cref="NodeDelegationWrapper"/>.
/// </summary>
/// <param name="innerNode">
/// The <see cref="INode"/> to delegate to.
/// </param>
/// <param name="resolver">
/// The resolver used to delegate <c>Resolve</c> calls.
/// </param>
/// <param name="nodeAdapter">
/// The adapter that will adapt adapter candidate nodes returned be the
/// <c>Resolve</c> and <c>ParentDirectory</c> methods.
/// </param>
protected NodeDelegationWrapper(INode innerNode, INodeResolver resolver, Converter<INode, INode> nodeAdapter)
: base(innerNode)
{
if (resolver == null)
{
if (this.NodeType == NodeType.Directory)
{
resolver = new DefaultResolver(this);
}
else
{
resolver = new DefaultResolver(this);
}
}
this.NodeResolver = resolver;
this.NodeAdapter = nodeAdapter;
}
/// <summary>
/// Overrides and returns the current node delegater's name.
/// </summary>
/// <remarks>
/// This property delegates to <c>this.Address.Name</c>
/// </remarks>
public override string Name
{
get
{
return this.Address.Name;
}
}
/// <summary>
/// Overrides and returns the current node's parent directory
/// optionally adapting the return result using the current
/// object's <see cref="NodeAdapter"/>.
/// </summary>
public override IDirectory ParentDirectory
{
get
{
return (IDirectory)NodeAdapter(this.Wrappee.ParentDirectory);
}
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override IFile ResolveFile(string name)
{
return this.NodeResolver.ResolveFile(name);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override IDirectory ResolveDirectory(string name)
{
return this.NodeResolver.ResolveDirectory(name);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override IFile ResolveFile(string name, AddressScope scope)
{
return this.NodeResolver.ResolveFile(name, scope);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override IDirectory ResolveDirectory(string name, AddressScope scope)
{
return this.NodeResolver.ResolveDirectory(name, scope);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override INode Resolve(string name)
{
return this.NodeResolver.Resolve(name);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override INode Resolve(string name, AddressScope scope)
{
return this.NodeResolver.Resolve(name, scope);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override INode Resolve(string name, NodeType nodeType)
{
return this.NodeResolver.Resolve(name, nodeType);
}
/// <summary>
/// Resolves a file using the current object's <see cref="NodeResolver"/>.
/// </summary>
/// <remarks>
/// The default implementation delegates to
/// <see cref="Resolve(string, NodeType, AddressScope)"/>.
/// </remarks>
public override INode Resolve(string name, NodeType nodeType, AddressScope scope)
{
return this.NodeResolver.Resolve(name, nodeType, scope);
}
/// <summary>
/// Overrides and returns the current node's
/// <see cref="INode.OperationTargetDirectory"/>
/// and adaptes the return result using the current
/// object's <see cref="NodeAdapter"/>.
/// </summary>
public override IDirectory OperationTargetDirectory
{
get
{
return (IDirectory)NodeAdapter(this.Wrappee.OperationTargetDirectory);
}
}
/// <summary>
/// Simulates delegation by comparing the delegator's (this) <c>INodeAddress</c>
/// and <c>NodeType</c>.
/// </summary>
/// <remarks>
/// Uses <c>this.Address</c> and <c>this.NodeType</c>.
/// </remarks>
public override bool Equals(object obj)
{
var node = obj as INode;
if (obj == null)
{
return false;
}
if (obj == this)
{
return true;
}
return this.NodeType.Equals(node.NodeType) && this.Address.Equals(node.Address);
}
/// <summary>
/// Gets the hashcode based on the delegator's (this) <c>INodeAddress</c>.
/// </summary>
public override int GetHashCode()
{
return this.Address.GetHashCode();
}
/// <summary>
/// Returns a string representation of the object using the delegator's (this) <c>INodeAddress</c>.
/// </summary>
public override string ToString()
{
return this.Address.ToString();
}
public override int CompareTo(INode other)
{
return System.String.Compare(this.Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
public override void CheckAccess(FileSystemSecuredOperation operation)
{
if (!this.FileSystem.SecurityManager.CurrentContext.HasAccess
(
new AccessVerificationContext(this, operation)
))
{
throw new FileSystemSecurityException(this.Address);
}
}
public override INode GetDirectoryOperationTargetNode(IDirectory directory)
{
return NodeAdapter(this.Wrappee.GetDirectoryOperationTargetNode(directory));
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Xml;
using System.Text;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Collections;
using OpenSource.UPnP.AV;
using OpenSource.Utilities;
using System.Runtime.Serialization;
using OpenSource.UPnP.AV.CdsMetadata;
namespace OpenSource.UPnP.AV.MediaServer.CP
{
/// <summary>
/// <para>
/// This class inherits all basic metadata of a ContentDirectory media item entry
/// (representing "object.item" and derived UPNP media classes),
/// for use in representing such objects for control-point interactions.
/// </para>
///
/// <para>
/// The state of CpMediaItem objects is largely managed through the
/// <see cref="CpMediaServer"/>
/// class. On occasions where the content hierarchy of the remote MediaServer
/// needs modification, the programmer can use the
/// <see cref="OpenSource.UPnP.AV.CdsMetadata.MediaBuilder"/>.CreateCpXXX methods
/// to instantiate media items to enable such interactions. Such
/// programming scenarios follow this general pattern.
/// <list type="number">
/// <item>
/// <description>Programmer instantiates a CpMediaXXX object and sets the desired metadata appropriately.</description>
/// </item>
/// <item>
/// <description>Programmer calls a RequstXXX method on a CpMediaContainer or CpRootContainer, passing the CpMediaXXX object as a parameter.</description>
/// </item>
/// <item>
/// <description>The framework translates the programmatic interaction into a UPNP ContentDirectory action request.</description>
/// </item>
/// <item>
/// <description>The remote MediaServer approves or denies the request, eventing the changes appropriately.</description>
/// </item>
/// <item>
/// <description>The <see cref="CpMediaServer"/>
/// consumes those notifications and updates the virtualized content hierarchy
/// for the control point application.</description>
/// </item>
/// </list>
/// </para>
/// <para>
/// It should be noted that this class has been largely designed for use with
/// <see cref="MediaServerDiscovery"/>, <see cref="ContainerDiscovery"/>,
/// <see cref="CpMediaContainer"/> and <see cref="CdsSpider"/>.
/// The class has evolved to be a resource
/// that can be shared amongst multiple plug-in DLL/applications that
/// use the same memory space. The <see cref="CdsSpider"/> objects help
/// turn this static-shared resource into an application/dll resource
/// by specifying which items and containers are of interest.
/// </para>
/// <para>
/// When a spider starts monitoring a container, the container
/// will notify the spiders of child objects (which can include
/// instances of <see cref="CpMediaItem"/> that would be of interest
/// to the spider. Similarly, the container will notify the spiders
/// of any child objects that have disappeared.
/// </para>
/// <para>
/// When this a container notifies a spider that this item
/// is of interest to the spider, the item is marked as match
/// and an internal counter is incremented to indicate the total
/// number of spiders that want this item persisted.
/// If an item ever reaches a state where zero spiders have marked the item
/// as a match, then the item is no longer persisted by the
/// parent container.
/// </para>
/// <para>
/// Which thus leads to a particular warning to programmers. Programmers
/// are responsible for using spiders to maintain the content hierarchy branches
/// of interest to them. If an application configures a spider to
/// monitor a particular container, and no spiders have been configured
/// to monitor any of the ancestor containers, then its very likely that
/// the spider-monitored container will be removed from its parent.
/// </para>
/// </summary>
[Serializable()]
public sealed class CpMediaItem : MediaItem, IUPnPMedia, ICpMedia, ICpItem
{
/// <summary>
/// Special ISerializable constructor.
/// Do basic initialization and then serialize from the info object.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
private CpMediaItem(SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base (info, context)
{
// Base class constructor calls Init() so all fields are
// initialized. Nothing else was serialized.
}
/// <summary>
/// Custom serializer - required for ISerializable.
/// Serializes all fields that are not marked as [NonSerialized()].
/// Some fields were originally marked as [NonSerialized()] because
/// this class did not implement ISerializable. I've continued to
/// use the attribute in the code.
///
/// CpMediaContainer objects do not serialize their child objects,
/// information about spiders, or the
/// <see cref="CpMediaItem.GetUnderlyingItem"/> field.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
public override void GetObjectData(SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
// nothing in addition to serialize
}
/// <summary>
/// Calls base class implementation of Init()
/// and then initializes fields for this class.
/// </summary>
protected override void Init()
{
base.Init();
this.GetUnderlyingItem = null;
this.m_SpiderClients = 0;
}
/// <summary>
/// Override set: Prevents public acess to set on property.
/// </summary>
public override string Creator
{
get
{
return base.Creator;
}
set
{
this.CheckRuntimeBindings(new StackTrace());
base.Creator = value;
}
}
/// <summary>
/// Override set: Prevents public acess to set on property.
/// </summary>
public override string Title
{
get
{
return base.Title;
}
set
{
this.CheckRuntimeBindings(new StackTrace());
base.Title = value;
}
}
/// <summary>
/// Override set: Prevents public acess to set on property.
/// </summary>
public override string ID
{
get
{
return base.ID;
}
set
{
this.CheckRuntimeBindings(new StackTrace());
base.ID = value;
}
}
/// <summary>
/// Calls base class implementation for get.
/// Checks access rights first and then calls base class implementation for set.
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
public override IMediaContainer Parent
{
get
{
return base.Parent;
}
set
{
this.CheckRuntimeBindings(new StackTrace());
base.Parent = value;
}
}
/// <summary>
/// <para>
/// This constructor calls the base class constructor(XmlElement), and
/// if and only if the type of the instances is a DvMediaItem will
/// the constructor call the base class implementation of UpdateEverything().
/// Any derived classes that use this constructor will have to make the
/// calls to UpdateEverything() if appropriate.
/// </para>
/// </summary>
/// <param name="xmlElement">XmlElement representing a DIDL-Lite item element</param>
public CpMediaItem (XmlElement xmlElement)
: base (xmlElement)
{
}
/// <summary>
/// Makes it so that a CpMediaItem instantiated from an XmlElement
/// instantiates its child resources as <see cref="CpMediaResource"/> objects.
///
/// <para>
/// Derived classes that expect different types for their resources and child
/// media objects need to override this method.
/// </para>
/// </summary>
/// <param name="xmlElement"></param>
protected override void FinishInitFromXml(XmlElement xmlElement)
{
ArrayList children;
base.UpdateEverything(true, true, typeof(CpMediaResource), typeof(CpMediaItem), typeof(CpMediaContainer), xmlElement, out children);
}
/// <summary>
/// Default constructor. No metadata is initialized in this
/// method. It is STRONGLY recommended that programmers
/// use the <see cref="CpMediaBuilder"/>.CreateXXX methods to instantiate
/// CpMediaItem objects.
/// </summary>
public CpMediaItem() : base()
{
}
/// <summary>
/// Returns true, if the item is a reference to another item.
/// </summary>
public override bool IsReference
{
get
{
return (this.m_RefID != "");
}
}
/// <summary>
/// Override set to prevent access to public programmers.
/// </summary>
/// <exception cref="Error_MetadataCallerViolation">
/// Thrown when the stack trace indicates the caller
/// was not defined in this namespace and assembly.
/// </exception>
public override bool IsRestricted
{
get
{
return base.IsRestricted;
}
set
{
CpMediaContainer p = this.Parent as CpMediaContainer;
if (p != null)
{
p.CheckRuntimeBindings(new StackTrace());
}
base.IsRestricted = value;
}
}
/// <summary>
/// Returns the ID of the referred item. If the item
/// does not reference anything, it returns the empty string.
/// Set only allows internal callers.
/// </summary>
/// <exception cref="Error_MetadataCallerViolation">
/// Thrown if set() caller is not internal to assembly/namespace.
/// </exception>
public override string RefID
{
get
{
return this.m_RefID;
}
set
{
this.CheckRuntimeBindings(new StackTrace());
this.m_RefID = value;
}
}
/// <summary>
/// If the item is a reference item, it can have two generalized states:
/// Valid or Invalid. If the state is valid, then the referred item is
/// has been virtualized and its metadata can be obtained. Otherwise,
/// the state is invalid and attempting to retrieve referred item's metadata
/// will cause errors. This method always returns true if the item is not a reference.
/// </summary>
public bool IsValid
{
get
{
if (IsReference == false)
{
return true;
}
return (this.RefItem != null);
}
}
/// <summary>
/// This method will invoke a CDS browse request and provide the results
/// directly the application-caller.
/// <para>
/// Implementation simply calls the parent owner's implementation of
/// <see cref="CpMediaContainer.RequestBrowse "/>(ICpMedia, CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag, string, uint, uint, string).
/// </para>
/// </summary>
/// <param name="BrowseFlag">browse metadata or direct children</param>
/// <param name="Filter">
/// Comma-separated value list of metadata names to include
/// in the response. For all metadata, use * character.
/// </param>
/// <param name="StartingIndex">
/// If obtaining children, the start index of the results.
/// Otherwise set to zero.
/// </param>
/// <param name="RequestedCount">
/// If obtaining children the max number of child objects
/// to retrieve. Otherwise use zero.
/// </param>
/// <param name="SortCriteria">
/// Comma-separated value list of metadata names to use for
/// sorting, such that preceding each metadata name (but after
/// the comma) a + or - character is present to indicate
/// ascending or descending sort order for that property.
/// </param>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">the callback to execute when results become available</param>
/// <exception cref="ApplicationException">
/// Thrown if the BrowseFlag value is BrowseDirectChildren because only the
/// object's metadata can be obtained use browse.
/// </exception>
public void RequestBrowse (CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag BrowseFlag, string Filter, uint StartingIndex, uint RequestedCount, string SortCriteria, object Tag, CpMediaDelegates.Delegate_ResultBrowse callback)
{
if (BrowseFlag == CpContentDirectory.Enum_A_ARG_TYPE_BrowseFlag.BROWSEDIRECTCHILDREN)
{
throw new ApplicationException("BrowseFlag cannot be BROWSEDIRECTCHILDREN");
}
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.RequestBrowse(this, BrowseFlag, Filter, StartingIndex, RequestedCount, SortCriteria, Tag, callback);
}
/// <summary>
/// Simply calls the owner object's implementation of Update().
/// </summary>
/// <exception cref="NullReferenceException">
/// Thrown if the parent object is null.
/// </exception>
/// <exception cref="InvalidCastException">
/// Thrown if the parent object is not a <see cref="CpMediaContainer"/>,
/// which should always be the case.
/// </exception>
public void Update ()
{
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.Update();
}
/// <summary>
/// Allows a programmer to request a remote mediaserver to change the metadata
/// for this item.
/// </summary>
/// <param name="useThisMetadata">
/// Media object that represents what the new metadata should be for the object.
/// </param>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">
/// Delegate executes when the results for the method are available.
/// </param>
/// <exception cref="Error_CannotGetParent">
/// Thrown if the parent of this object is null.
/// </exception>
/// <exception cref="InvalidCastException">
/// Thrown if this object's parent is not a
/// <see cref="CpMediaContainer"/> object.
/// </exception>
public void RequestUpdateObject (IUPnPMedia useThisMetadata, object Tag, CpMediaDelegates.Delegate_ResultUpdateObject callback)
{
CpMediaContainer p = (CpMediaContainer) this.Parent;
if (p != null)
{
p.RequestUpdateObject(this, useThisMetadata, Tag, callback);
}
else
{
throw new Error_CannotGetParent(this);
}
}
/// <summary>
/// Makes a request on the remote media server to delete this
/// object from its parent.
/// </summary>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">
/// Delegate executes when the results for the method are available.
/// </param>
/// <exception cref="Error_CannotGetParent">
/// Thrown if the parent of this object is null.
/// </exception>
/// <exception cref="InvalidCastException">
/// Thrown if this object's parent is not a
/// <see cref="CpMediaContainer"/> object.
/// </exception>
public void RequestDestroyObject (object Tag, CpMediaDelegates.Delegate_ResultDestroyObject callback)
{
CpMediaContainer p = (CpMediaContainer) this.Parent;
if (p != null)
{
p.RequestDestroyObject(this, Tag, callback);
}
else
{
throw new Error_CannotGetParent(this);
}
}
/// <summary>
/// Requests a remote media server to delete a resource from its local file system.
/// </summary>
/// <param name="deleteThisResource">the resource to request for deletion</param>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">callback to execute when results have been obtained</param>
/// <exception cref="Error_ResourceNotOnServer">
/// Thrown when attempting to delete a resource object that
/// is not part of the server's content hierarchy.
/// </exception>
/// <exception cref="NullReferenceException">
/// Thrown when attempting a remove a resource that has
/// a null/empty value for its contentUri.
/// </exception>
/// <exception cref="Error_CannotGetParent">
/// Thrown if the parent of this object is null.
/// </exception>
/// <exception cref="InvalidCastException">
/// Thrown if the parent of this object is not a <see cref="CpMediaContainer"/>.
/// </exception>
public void RequestDeleteResource(ICpResource deleteThisResource, object Tag, CpMediaDelegates.Delegate_ResultDeleteResource callback)
{
// calls parent's implementation of method
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.RequestDeleteResource(deleteThisResource, Tag, callback);
}
/// <summary>
/// Makes a request to a remote media server to export one of its binary files
/// to another location.
/// </summary>
/// <param name="exportThis">
/// The resource (of this media object) that should be exported.
/// </param>
/// <param name="sendHere">
/// The uri where the binary should be sent.
/// </param>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">the callback to execute when results become available</param>
/// <exception cref="Error_CannotGetParent">
/// Thrown if the parent of this object is null.
/// </exception>
public void RequestExportResource(ICpResource exportThis, System.Uri sendHere, object Tag, CpMediaDelegates.Delegate_ResultExportResource callback)
{
// calls parent's implementation of method
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.RequestExportResource(exportThis, sendHere, Tag, callback);
}
/// <summary>
/// Makes a request to a remote media server to import the binary file from a URI to
/// a resource that is part of the server's content hierarchy.
/// </summary>
/// <param name="sourceUri">the URI where binary should be pulled</param>
/// <param name="importHere">the <see cref="ICpResource"/> object that represents the
/// destination of the imported binary
/// </param>
/// <param name="Tag">
/// Miscellaneous, user-provided object for tracking this
/// asynchronous call. Can be used as a means to pass a
/// user-defined "state object" at invoke-time so that
/// the executed callback during results-processing can be
/// aware of the component's state at the time of the call.
/// </param>
/// <param name="callback">the callback to execute when results become available</param>
/// <exception cref="Error_ResourceNotOnServer">
/// Thrown when attempting to delete a resource object that
/// is not part of the server's content hierarchy.
/// </exception>
/// <exception cref="NullReferenceException">
/// Thrown when attempting a remove a resource that has
/// a null/empty value for its contentUri.
/// </exception>
/// <exception cref="Error_CannotGetParent">
/// Thrown if the parent of this object is null.
/// </exception>
/// <exception cref="InvalidCastException">
/// Thrown if the parent of this object is not a <see cref="CpMediaContainer"/>.
/// </exception>
public void RequestImportResource (System.Uri sourceUri, ICpResource importHere, object Tag, CpMediaDelegates.Delegate_ResultImportResource callback)
{
// calls parent's implementation of method
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.RequestImportResource(sourceUri, importHere, Tag, callback);
}
/// <summary>
/// Calls the parent object's implementation of <see cref="CpMediaContainer.CheckRuntimeBindings"/>.
/// </summary>
/// <param name="st">stack trace object, created in the method that desires runtime checking</param>
public override void CheckRuntimeBindings(StackTrace st)
{
if (this.Parent != null)
{
CpMediaContainer parent = (CpMediaContainer) this.Parent;
parent.CheckRuntimeBindings(st);
}
}
/// <summary>
/// Control-point applications are never guaranteed to know the underlying
/// item of a refererring item. For this reason, the LookupRefItem() method
/// is overridden to do a lookup of the referred item any item the
/// referred item is requested.
/// </summary>
/// <returns>an instance of CpMediaItem, if the referred item was found</returns>
public override IMediaItem RefItem
{
get
{
if (this.GetUnderlyingItem != null)
{
return this.GetUnderlyingItem(this, this.m_RefID);
}
else
{
return null;
}
}
set
{
this.CheckRuntimeBindings(new StackTrace());
}
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="addThis">the CpMediaResource object with a corresponding resource advertised by the MediaServer</param>
/// <exception cref="InvalidCastException">
/// Thrown when attempting to add a non-CpMediaResource object to this container.
/// </exception>
public override void AddResource(IMediaResource addThis)
{
this.CheckRuntimeBindings(new StackTrace());
CpMediaResource res = (CpMediaResource) addThis;
base.AddResource(addThis);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="removeThis">the MediaResource to remove</param>
public override void RemoveResource(IMediaResource removeThis)
{
this.CheckRuntimeBindings(new StackTrace());
base.RemoveResource(removeThis);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="newResources">a collection of CpMediaResource</param>
/// <exception cref="InvalidCastException">
/// Thrown when attempting to add a non-CpMediaResource object to this container.
/// </exception>
public override void AddResources(ICollection newResources)
{
this.CheckRuntimeBindings(new StackTrace());
foreach (CpMediaResource res in newResources);
this.m_LockResources.AcquireWriterLock(-1);
base.AddResources(newResources);
this.m_LockResources.ReleaseWriterLock();
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="removeThese"></param>
public override void RemoveResources(ICollection removeThese)
{
this.CheckRuntimeBindings(new StackTrace());
base.RemoveResources(removeThese);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </para>
/// </summary>
/// <param name="element">The metadata block must be in xml form.</param>
public override void AddDescNode(string element)
{
this.CheckRuntimeBindings(new StackTrace());
base.AddDescNode(element);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </para>
/// </summary>
/// <param name="elements">The metadata blocks must be in xml form.</param>
public override void AddDescNode(string[] elements)
{
this.CheckRuntimeBindings(new StackTrace());
base.AddDescNode(elements);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="element">The metadata blocks must be in xml form.</param>
public override void RemoveDescNode(string element)
{
this.CheckRuntimeBindings(new StackTrace());
base.RemoveDescNode(element);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// <para>
/// After checking the caller's binding/permissions, the method
/// simply calls <see cref="MediaObject.UpdateEverything"/>
/// with the following code
/// <code>
/// ArrayList proposedChildren;
/// this.UpdateEverything(false, false, typeof(CpMediaResource), typeof(CpMediaItem), typeof(CpMediaContainer), xmlElement, out proposedChildren);
/// </code>
/// </para>
/// </summary>
/// <param name="xmlElement"></param>
public override void UpdateMetadata(XmlElement xmlElement)
{
this.CheckRuntimeBindings(new StackTrace());
ArrayList proposedChildren;
this.UpdateEverything(false, false, typeof(CpMediaResource), typeof(CpMediaItem), typeof(CpMediaContainer), xmlElement, out proposedChildren);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="DidlLiteXml"></param>
public override void UpdateMetadata(string DidlLiteXml)
{
this.CheckRuntimeBindings(new StackTrace());
base.UpdateMetadata(DidlLiteXml);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="newObj"></param>
public override void UpdateObject(IUPnPMedia newObj)
{
this.CheckRuntimeBindings(new StackTrace());
base.UpdateObject(newObj);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// <para>
/// After checking the caller's binding/permissions, the method
/// simply calls <see cref="MediaObject.UpdateEverything"/>
/// with the following code
/// <code>
/// ArrayList proposedChildren;
/// this.UpdateEverything(true, false, typeof(CpMediaResource), typeof(CpMediaItem), typeof(CpMediaContainer), xmlElement, out proposedChildren);
/// </code>
/// </para>
/// </summary>
/// <param name="xmlElement"></param>
public override void UpdateObject(XmlElement xmlElement)
{
this.CheckRuntimeBindings(new StackTrace());
ArrayList proposedChildren;
this.UpdateEverything(true, false, typeof(CpMediaResource), typeof(CpMediaItem), typeof(CpMediaContainer), xmlElement, out proposedChildren);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="DidlLiteXml"></param>
public override void UpdateObject (string DidlLiteXml)
{
this.CheckRuntimeBindings(new StackTrace());
base.UpdateObject(DidlLiteXml);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="writeStatus"></param>
public override void SetWriteStatus(EnumWriteStatus writeStatus)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetWriteStatus(writeStatus);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="classType"></param>
/// <param name="friendlyName"></param>
public override void SetClass(string classType, string friendlyName)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetClass(classType, friendlyName);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="values"></param>
public override void SetPropertyValue (string propertyName, IList values)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue (propertyName, values);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="values"></param>
public override void SetPropertyValue_String(string propertyName, string[] values)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_String (propertyName, values);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="val"></param>
public override void SetPropertyValue_String(string propertyName, string val)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_String(propertyName, val);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="values"></param>
public override void SetPropertyValue_Int(string propertyName, int[] values)
{
this.CheckRuntimeBindings(new StackTrace());
this.SetPropertyValue_Int(propertyName, values);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="val"></param>
public override void SetPropertyValue_Int(string propertyName, int val)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_Int(propertyName, val);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="values"></param>
public override void SetPropertyValue_Long(string propertyName, long[] values)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_Long(propertyName, values);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="val"></param>
public override void SetPropertyValue_Long(string propertyName, long val)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_Long(propertyName, val);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="values"></param>
public override void SetPropertyValue_MediaClass(string propertyName, MediaClass[] values)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_MediaClass(propertyName, values);
}
/// <summary>
/// The ability to modify objects directly to a container/item is not available
/// for a public programmer. Each CpMediaItem object is responsible
/// for maintaining its own state.
/// </summary>
/// <param name="propertyName"></param>
/// <param name="val"></param>
public override void SetPropertyValue_MediaClass(string propertyName, MediaClass val)
{
this.CheckRuntimeBindings(new StackTrace());
base.SetPropertyValue_MediaClass(propertyName, val);
}
/// <summary>
/// Increments the number of spiders that have indicated
/// this item to be of interest to them.
/// This method is called by Sink_ResultBrowse.
/// </summary>
internal void IncrementSpiderMatches()
{
System.Threading.Interlocked.Increment(ref this.m_SpiderClients);
}
/// <summary>
/// Decrements the number of spiders that have indicated
/// this item to be of interest to them.
/// This method is called by CdsSpider to indicate
/// that the spider is not interested in the container anymore.
/// If no spiders are interested in the item, then
/// the item is removed.
/// </summary>
internal void DecrementSpiderMatches()
{
System.Threading.Interlocked.Decrement(ref this.m_SpiderClients);
if (this.m_SpiderClients == 0)
{
CpMediaContainer p = (CpMediaContainer) this.Parent;
if (p != null)
{
p.RemoveObject(this);
}
}
}
/// <summary>
/// Sets the container to a new parent.
/// </summary>
/// <param name="newParent"></param>
internal void SetParent(CpMediaContainer newParent)
{
this.m_Parent = newParent;
}
/// <summary>
/// Indicates that no spiders have marked this item to remain in memory.
/// </summary>
internal bool PleaseRemove
{
get
{
return this.m_bools[(int) EnumBoolsCpMediaItem.PleaseRemove];
}
set
{
this.m_bools[(int) EnumBoolsCpMediaItem.PleaseRemove] = value;
}
}
/// <summary>
/// The number of spiders that are interested in this item.
/// </summary>
[NonSerialized()] private long m_SpiderClients = 0;
public long SpiderClients { get { return this.m_SpiderClients; } }
/// <summary>
/// Enumerates through m_bools
/// </summary>
private enum EnumBoolsCpMediaItem
{
PleaseRemove = MediaItem.EnumBoolsMediaItem.IgnoreLast,
IgnoreLast
}
/// <summary>
/// This delegate is a means to perform a lookup on a application managed table
/// of <see cref="CpMediaItem"/> objects.
/// Programmers who wish to allow <see cref="CpMediaItem"/> to know about
/// their underlying items will need to track that information themselves
/// and wire this delegate up to a method that will return the appropriate
/// object for a given item id.
/// </summary>
[NonSerialized()] public LookupUnderlyingItemHandler GetUnderlyingItem = null;
/// <summary>
/// Used for GetUnderlyingItem field.
/// </summary>
public delegate CpMediaItem LookupUnderlyingItemHandler (CpMediaItem caller, string itemID);
/// <summary>
/// A static reference to the type of a CpMediaResource instance.
/// </summary>
private static System.Type TYPE_CP_RESOURCE = typeof (CpMediaResource);
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.ComponentModel;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Security;
using System.Xml;
public sealed class ReliableSessionBindingElement : BindingElement, IPolicyExportExtension
{
TimeSpan acknowledgementInterval = ReliableSessionDefaults.AcknowledgementInterval;
bool flowControlEnabled = ReliableSessionDefaults.FlowControlEnabled;
TimeSpan inactivityTimeout = ReliableSessionDefaults.InactivityTimeout;
int maxPendingChannels = ReliableSessionDefaults.MaxPendingChannels;
int maxRetryCount = ReliableSessionDefaults.MaxRetryCount;
int maxTransferWindowSize = ReliableSessionDefaults.MaxTransferWindowSize;
bool ordered = ReliableSessionDefaults.Ordered;
ReliableMessagingVersion reliableMessagingVersion = ReliableMessagingVersion.Default;
InternalDuplexBindingElement internalDuplexBindingElement;
static MessagePartSpecification bodyOnly;
public ReliableSessionBindingElement()
{
}
internal ReliableSessionBindingElement(ReliableSessionBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
this.AcknowledgementInterval = elementToBeCloned.AcknowledgementInterval;
this.FlowControlEnabled = elementToBeCloned.FlowControlEnabled;
this.InactivityTimeout = elementToBeCloned.InactivityTimeout;
this.MaxPendingChannels = elementToBeCloned.MaxPendingChannels;
this.MaxRetryCount = elementToBeCloned.MaxRetryCount;
this.MaxTransferWindowSize = elementToBeCloned.MaxTransferWindowSize;
this.Ordered = elementToBeCloned.Ordered;
this.ReliableMessagingVersion = elementToBeCloned.ReliableMessagingVersion;
this.internalDuplexBindingElement = elementToBeCloned.internalDuplexBindingElement;
}
public ReliableSessionBindingElement(bool ordered)
{
this.ordered = ordered;
}
[DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.AcknowledgementIntervalString)]
public TimeSpan AcknowledgementInterval
{
get
{
return this.acknowledgementInterval;
}
set
{
if (value <= TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.acknowledgementInterval = value;
}
}
[DefaultValue(ReliableSessionDefaults.FlowControlEnabled)]
public bool FlowControlEnabled
{
get
{
return this.flowControlEnabled;
}
set
{
this.flowControlEnabled = value;
}
}
[DefaultValue(typeof(TimeSpan), ReliableSessionDefaults.InactivityTimeoutString)]
public TimeSpan InactivityTimeout
{
get
{
return this.inactivityTimeout;
}
set
{
if (value <= TimeSpan.Zero)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.TimeSpanMustbeGreaterThanTimeSpanZero)));
}
if (TimeoutHelper.IsTooLarge(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.SFxTimeoutOutOfRangeTooBig)));
}
this.inactivityTimeout = value;
}
}
[DefaultValue(ReliableSessionDefaults.MaxPendingChannels)]
public int MaxPendingChannels
{
get
{
return this.maxPendingChannels;
}
set
{
if (value <= 0 || value > 16384)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeInRange, 0, 16384)));
this.maxPendingChannels = value;
}
}
[DefaultValue(ReliableSessionDefaults.MaxRetryCount)]
public int MaxRetryCount
{
get
{
return this.maxRetryCount;
}
set
{
if (value <= 0)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBePositive)));
this.maxRetryCount = value;
}
}
[DefaultValue(ReliableSessionDefaults.MaxTransferWindowSize)]
public int MaxTransferWindowSize
{
get
{
return this.maxTransferWindowSize;
}
set
{
if (value <= 0 || value > 4096)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value,
SR.GetString(SR.ValueMustBeInRange, 0, 4096)));
this.maxTransferWindowSize = value;
}
}
[DefaultValue(ReliableSessionDefaults.Ordered)]
public bool Ordered
{
get
{
return this.ordered;
}
set
{
this.ordered = value;
}
}
[DefaultValue(typeof(ReliableMessagingVersion), ReliableSessionDefaults.ReliableMessagingVersionString)]
public ReliableMessagingVersion ReliableMessagingVersion
{
get
{
return this.reliableMessagingVersion;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
if (!ReliableMessagingVersion.IsDefined(value))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
}
this.reliableMessagingVersion = value;
}
}
static MessagePartSpecification BodyOnly
{
get
{
if (bodyOnly == null)
{
MessagePartSpecification temp = new MessagePartSpecification(true);
temp.MakeReadOnly();
bodyOnly = temp;
}
return bodyOnly;
}
}
public override BindingElement Clone()
{
return new ReliableSessionBindingElement(this);
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(ChannelProtectionRequirements))
{
ChannelProtectionRequirements myRequirements = this.GetProtectionRequirements();
myRequirements.Add(context.GetInnerProperty<ChannelProtectionRequirements>() ?? new ChannelProtectionRequirements());
return (T)(object)myRequirements;
}
else if (typeof(T) == typeof(IBindingDeliveryCapabilities))
{
return (T)(object)new BindingDeliveryCapabilitiesHelper(this, context.GetInnerProperty<IBindingDeliveryCapabilities>());
}
else
{
return context.GetInnerProperty<T>();
}
}
ChannelProtectionRequirements GetProtectionRequirements()
{
// Listing headers that must be signed.
ChannelProtectionRequirements result = new ChannelProtectionRequirements();
MessagePartSpecification signedReliabilityMessageParts = WsrmIndex.GetSignedReliabilityMessageParts(
this.reliableMessagingVersion);
result.IncomingSignatureParts.AddParts(signedReliabilityMessageParts);
result.OutgoingSignatureParts.AddParts(signedReliabilityMessageParts);
if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
// Adding RM protocol message actions so that each RM protocol message's body will be
// signed and encrypted.
// From the Client to the Service
ScopedMessagePartSpecification signaturePart = result.IncomingSignatureParts;
ScopedMessagePartSpecification encryptionPart = result.IncomingEncryptionParts;
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.AckRequestedAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.CreateSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.SequenceAcknowledgementAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.LastMessageAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.TerminateSequenceAction);
// From the Service to the Client
signaturePart = result.OutgoingSignatureParts;
encryptionPart = result.OutgoingEncryptionParts;
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.CreateSequenceResponseAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.SequenceAcknowledgementAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.LastMessageAction);
ProtectProtocolMessage(signaturePart, encryptionPart, WsrmFeb2005Strings.TerminateSequenceAction);
}
else if (this.reliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
{
// Adding RM protocol message actions so that each RM protocol message's body will be
// signed and encrypted.
// From the Client to the Service
ScopedMessagePartSpecification signaturePart = result.IncomingSignatureParts;
ScopedMessagePartSpecification encryptionPart = result.IncomingEncryptionParts;
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.AckRequestedAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceResponseAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CreateSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.FaultAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.SequenceAcknowledgementAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceResponseAction);
// From the Service to the Client
signaturePart = result.OutgoingSignatureParts;
encryptionPart = result.OutgoingEncryptionParts;
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.AckRequestedAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CloseSequenceResponseAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.CreateSequenceResponseAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.FaultAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.SequenceAcknowledgementAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceAction);
ProtectProtocolMessage(signaturePart, encryptionPart, Wsrm11Strings.TerminateSequenceResponseAction);
}
else
{
throw Fx.AssertAndThrow("Reliable messaging version not supported.");
}
return result;
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
this.VerifyTransportMode(context);
this.SetSecuritySettings(context);
InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref this.internalDuplexBindingElement);
if (typeof(TChannel) == typeof(IOutputSessionChannel))
{
if (context.CanBuildInnerChannelFactory<IRequestSessionChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IRequestSessionChannel>(
this, context.BuildInnerChannelFactory<IRequestSessionChannel>(), context.Binding);
}
else if (context.CanBuildInnerChannelFactory<IRequestChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IRequestChannel>(
this, context.BuildInnerChannelFactory<IRequestChannel>(), context.Binding);
}
else if (context.CanBuildInnerChannelFactory<IDuplexSessionChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IDuplexSessionChannel>(
this, context.BuildInnerChannelFactory<IDuplexSessionChannel>(), context.Binding);
}
else if (context.CanBuildInnerChannelFactory<IDuplexChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IDuplexChannel>(
this, context.BuildInnerChannelFactory<IDuplexChannel>(), context.Binding);
}
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
if (context.CanBuildInnerChannelFactory<IDuplexSessionChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IDuplexSessionChannel>(
this, context.BuildInnerChannelFactory<IDuplexSessionChannel>(), context.Binding);
}
else if (context.CanBuildInnerChannelFactory<IDuplexChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IDuplexChannel>(
this, context.BuildInnerChannelFactory<IDuplexChannel>(), context.Binding);
}
}
else if (typeof(TChannel) == typeof(IRequestSessionChannel))
{
if (context.CanBuildInnerChannelFactory<IRequestSessionChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IRequestSessionChannel>(
this, context.BuildInnerChannelFactory<IRequestSessionChannel>(), context.Binding);
}
else if (context.CanBuildInnerChannelFactory<IRequestChannel>())
{
return (IChannelFactory<TChannel>)(object)
new ReliableChannelFactory<TChannel, IRequestChannel>(
this, context.BuildInnerChannelFactory<IRequestChannel>(), context.Binding);
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref this.internalDuplexBindingElement);
if (typeof(TChannel) == typeof(IOutputSessionChannel))
{
return context.CanBuildInnerChannelFactory<IRequestSessionChannel>()
|| context.CanBuildInnerChannelFactory<IRequestChannel>()
|| context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()
|| context.CanBuildInnerChannelFactory<IDuplexChannel>();
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()
|| context.CanBuildInnerChannelFactory<IDuplexChannel>();
}
else if (typeof(TChannel) == typeof(IRequestSessionChannel))
{
return context.CanBuildInnerChannelFactory<IRequestSessionChannel>()
|| context.CanBuildInnerChannelFactory<IRequestChannel>();
}
return false;
}
public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
this.VerifyTransportMode(context);
this.SetSecuritySettings(context);
#pragma warning suppress 56506 // BindingContext guarantees BindingParameters is never null.
IMessageFilterTable<EndpointAddress> table = context.BindingParameters.Find<IMessageFilterTable<EndpointAddress>>();
InternalDuplexBindingElement.AddDuplexListenerSupport(context, ref this.internalDuplexBindingElement);
if (typeof(TChannel) == typeof(IInputSessionChannel))
{
ReliableChannelListenerBase<IInputSessionChannel> listener = null;
if (context.CanBuildInnerChannelListener<IReplySessionChannel>())
{
listener = new ReliableInputListenerOverReplySession(this, context);
}
else if (context.CanBuildInnerChannelListener<IReplyChannel>())
{
listener = new ReliableInputListenerOverReply(this, context);
}
else if (context.CanBuildInnerChannelListener<IDuplexSessionChannel>())
{
listener = new ReliableInputListenerOverDuplexSession(this, context);
}
else if (context.CanBuildInnerChannelListener<IDuplexChannel>())
{
listener = new ReliableInputListenerOverDuplex(this, context);
}
if (listener != null)
{
listener.LocalAddresses = table;
return (IChannelListener<TChannel>)(object)listener;
}
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
ReliableChannelListenerBase<IDuplexSessionChannel> listener = null;
if (context.CanBuildInnerChannelListener<IDuplexSessionChannel>())
{
listener = new ReliableDuplexListenerOverDuplexSession(this, context);
}
else if (context.CanBuildInnerChannelListener<IDuplexChannel>())
{
listener = new ReliableDuplexListenerOverDuplex(this, context);
}
if (listener != null)
{
listener.LocalAddresses = table;
return (IChannelListener<TChannel>)(object)listener;
}
}
else if (typeof(TChannel) == typeof(IReplySessionChannel))
{
ReliableChannelListenerBase<IReplySessionChannel> listener = null;
if (context.CanBuildInnerChannelListener<IReplySessionChannel>())
{
listener = new ReliableReplyListenerOverReplySession(this, context);
}
else if (context.CanBuildInnerChannelListener<IReplyChannel>())
{
listener = new ReliableReplyListenerOverReply(this, context);
}
if (listener != null)
{
listener.LocalAddresses = table;
return (IChannelListener<TChannel>)(object)listener;
}
}
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("TChannel", SR.GetString(SR.ChannelTypeNotSupported, typeof(TChannel)));
}
public override bool CanBuildChannelListener<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
InternalDuplexBindingElement.AddDuplexListenerSupport(context, ref this.internalDuplexBindingElement);
if (typeof(TChannel) == typeof(IInputSessionChannel))
{
return context.CanBuildInnerChannelListener<IReplySessionChannel>()
|| context.CanBuildInnerChannelListener<IReplyChannel>()
|| context.CanBuildInnerChannelListener<IDuplexSessionChannel>()
|| context.CanBuildInnerChannelListener<IDuplexChannel>();
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return context.CanBuildInnerChannelListener<IDuplexSessionChannel>()
|| context.CanBuildInnerChannelListener<IDuplexChannel>();
}
else if (typeof(TChannel) == typeof(IReplySessionChannel))
{
return context.CanBuildInnerChannelListener<IReplySessionChannel>()
|| context.CanBuildInnerChannelListener<IReplyChannel>();
}
return false;
}
internal override bool IsMatch(BindingElement b)
{
if (b == null)
return false;
ReliableSessionBindingElement session = b as ReliableSessionBindingElement;
if (session == null)
return false;
if (this.acknowledgementInterval != session.acknowledgementInterval)
return false;
if (this.flowControlEnabled != session.flowControlEnabled)
return false;
if (this.inactivityTimeout != session.inactivityTimeout)
return false;
if (this.maxPendingChannels != session.maxPendingChannels)
return false;
if (this.maxRetryCount != session.maxRetryCount)
return false;
if (this.maxTransferWindowSize != session.maxTransferWindowSize)
return false;
if (this.ordered != session.ordered)
return false;
if (this.reliableMessagingVersion != session.reliableMessagingVersion)
return false;
return true;
}
static void ProtectProtocolMessage(
ScopedMessagePartSpecification signaturePart,
ScopedMessagePartSpecification encryptionPart,
string action)
{
signaturePart.AddParts(BodyOnly, action);
encryptionPart.AddParts(MessagePartSpecification.NoParts, action);
//encryptionPart.AddParts(BodyOnly, action);
}
void SetSecuritySettings(BindingContext context)
{
SecurityBindingElement element = context.RemainingBindingElements.Find<SecurityBindingElement>();
if (element != null)
{
element.LocalServiceSettings.ReconnectTransportOnFailure = true;
}
}
void VerifyTransportMode(BindingContext context)
{
TransportBindingElement transportElement = context.RemainingBindingElements.Find<TransportBindingElement>();
// Verify ManualAdderssing is turned off.
if ((transportElement != null) && (transportElement.ManualAddressing))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.ManualAddressingNotSupported)));
}
ConnectionOrientedTransportBindingElement connectionElement = transportElement as ConnectionOrientedTransportBindingElement;
HttpTransportBindingElement httpElement = transportElement as HttpTransportBindingElement;
// Verify TransportMode is Buffered.
TransferMode transportTransferMode;
if (connectionElement != null)
{
transportTransferMode = connectionElement.TransferMode;
}
else if (httpElement != null)
{
transportTransferMode = httpElement.TransferMode;
}
else
{
// Not one of the elements we can check, we have to assume TransferMode.Buffered.
transportTransferMode = TransferMode.Buffered;
}
if (transportTransferMode != TransferMode.Buffered)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(SR.GetString(SR.TransferModeNotSupported,
transportTransferMode, this.GetType().Name)));
}
}
void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
{
if (exporter == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
if (context.BindingElements != null)
{
BindingElementCollection bindingElements = context.BindingElements;
ReliableSessionBindingElement settings = bindingElements.Find<ReliableSessionBindingElement>();
if (settings != null)
{
// ReliableSession assertion
XmlElement assertion = settings.CreateReliabilityAssertion(exporter.PolicyVersion, bindingElements);
context.GetBindingAssertions().Add(assertion);
}
}
}
static XmlElement CreatePolicyElement(PolicyVersion policyVersion, XmlDocument doc)
{
string policy = MetadataStrings.WSPolicy.Elements.Policy;
string policyNs = policyVersion.Namespace;
string policyPrefix = MetadataStrings.WSPolicy.Prefix;
return doc.CreateElement(policyPrefix, policy, policyNs);
}
XmlElement CreateReliabilityAssertion(PolicyVersion policyVersion, BindingElementCollection bindingElements)
{
XmlDocument doc = new XmlDocument();
XmlElement child = null;
string reliableSessionPrefix;
string reliableSessionNs;
string assertionPrefix;
string assertionNs;
if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessagingFebruary2005)
{
reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Prefix;
reliableSessionNs = ReliableSessionPolicyStrings.ReliableSessionFebruary2005Namespace;
assertionPrefix = reliableSessionPrefix;
assertionNs = reliableSessionNs;
}
else
{
reliableSessionPrefix = ReliableSessionPolicyStrings.ReliableSession11Prefix;
reliableSessionNs = ReliableSessionPolicyStrings.ReliableSession11Namespace;
assertionPrefix = ReliableSessionPolicyStrings.NET11Prefix;
assertionNs = ReliableSessionPolicyStrings.NET11Namespace;
}
// ReliableSession assertion
XmlElement assertion = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ReliableSessionName, reliableSessionNs);
if (this.ReliableMessagingVersion == ReliableMessagingVersion.WSReliableMessaging11)
{
// Policy
XmlElement policy = CreatePolicyElement(policyVersion, doc);
// SequenceSTR
if (IsSecureConversationEnabled(bindingElements))
{
XmlElement sequenceSTR = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.SequenceSTR, reliableSessionNs);
policy.AppendChild(sequenceSTR);
}
// DeliveryAssurance
XmlElement deliveryAssurance = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.DeliveryAssurance, reliableSessionNs);
// Policy
XmlElement nestedPolicy = CreatePolicyElement(policyVersion, doc);
// ExactlyOnce
XmlElement exactlyOnce = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.ExactlyOnce, reliableSessionNs);
nestedPolicy.AppendChild(exactlyOnce);
if (this.ordered)
{
// InOrder
XmlElement inOrder = doc.CreateElement(reliableSessionPrefix, ReliableSessionPolicyStrings.InOrder, reliableSessionNs);
nestedPolicy.AppendChild(inOrder);
}
deliveryAssurance.AppendChild(nestedPolicy);
policy.AppendChild(deliveryAssurance);
assertion.AppendChild(policy);
}
// Nested InactivityTimeout assertion
child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.InactivityTimeout, assertionNs);
WriteMillisecondsAttribute(child, this.InactivityTimeout);
assertion.AppendChild(child);
// Nested AcknowledgementInterval assertion
child = doc.CreateElement(assertionPrefix, ReliableSessionPolicyStrings.AcknowledgementInterval, assertionNs);
WriteMillisecondsAttribute(child, this.AcknowledgementInterval);
assertion.AppendChild(child);
return assertion;
}
static bool IsSecureConversationEnabled(BindingElementCollection bindingElements)
{
bool foundRM = false;
for (int i = 0; i < bindingElements.Count; i++)
{
if (!foundRM)
{
ReliableSessionBindingElement bindingElement = bindingElements[i] as ReliableSessionBindingElement;
foundRM = (bindingElement != null);
}
else
{
SecurityBindingElement securityBindingElement = bindingElements[i] as SecurityBindingElement;
if (securityBindingElement != null)
{
SecurityBindingElement bootstrapSecurity;
// The difference in bool (requireCancellation) does not affect whether the binding is valid,
// but the method does match on the value so we need to pass both true and false.
return SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, true, out bootstrapSecurity)
|| SecurityBindingElement.IsSecureConversationBinding(securityBindingElement, false, out bootstrapSecurity);
}
break;
}
}
return false;
}
static void WriteMillisecondsAttribute(XmlElement childElement, TimeSpan timeSpan)
{
UInt64 milliseconds = Convert.ToUInt64(timeSpan.TotalMilliseconds);
childElement.SetAttribute(ReliableSessionPolicyStrings.Milliseconds, XmlConvert.ToString(milliseconds));
}
class BindingDeliveryCapabilitiesHelper : IBindingDeliveryCapabilities
{
ReliableSessionBindingElement element;
IBindingDeliveryCapabilities inner;
internal BindingDeliveryCapabilitiesHelper(ReliableSessionBindingElement element, IBindingDeliveryCapabilities inner)
{
this.element = element;
this.inner = inner;
}
bool IBindingDeliveryCapabilities.AssuresOrderedDelivery
{
get { return element.Ordered; }
}
bool IBindingDeliveryCapabilities.QueuedDelivery
{
get { return inner != null ? inner.QueuedDelivery : false; }
}
}
}
}
| |
namespace org.apache.http.conn
{
[global::MonoJavaBridge.JavaInterface(typeof(global::org.apache.http.conn.ManagedClientConnection_))]
public interface ManagedClientConnection : HttpClientConnection, HttpInetConnection, ConnectionReleaseTrigger
{
global::java.lang.Object getState();
void setState(java.lang.Object arg0);
void open(org.apache.http.conn.routing.HttpRoute arg0, org.apache.http.protocol.HttpContext arg1, org.apache.http.@params.HttpParams arg2);
bool isSecure();
global::org.apache.http.conn.routing.HttpRoute getRoute();
global::javax.net.ssl.SSLSession getSSLSession();
void tunnelTarget(bool arg0, org.apache.http.@params.HttpParams arg1);
void tunnelProxy(org.apache.http.HttpHost arg0, bool arg1, org.apache.http.@params.HttpParams arg2);
void layerProtocol(org.apache.http.protocol.HttpContext arg0, org.apache.http.@params.HttpParams arg1);
void markReusable();
void unmarkReusable();
bool isMarkedReusable();
void setIdleDuration(long arg0, java.util.concurrent.TimeUnit arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::org.apache.http.conn.ManagedClientConnection))]
public sealed partial class ManagedClientConnection_ : java.lang.Object, ManagedClientConnection
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ManagedClientConnection_()
{
InitJNI();
}
internal ManagedClientConnection_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _getState16326;
global::java.lang.Object org.apache.http.conn.ManagedClientConnection.getState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getState16326)) as java.lang.Object;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getState16326)) as java.lang.Object;
}
internal static global::MonoJavaBridge.MethodId _setState16327;
void org.apache.http.conn.ManagedClientConnection.setState(java.lang.Object arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._setState16327, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._setState16327, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _open16328;
void org.apache.http.conn.ManagedClientConnection.open(org.apache.http.conn.routing.HttpRoute arg0, org.apache.http.protocol.HttpContext arg1, org.apache.http.@params.HttpParams arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._open16328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._open16328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _isSecure16329;
bool org.apache.http.conn.ManagedClientConnection.isSecure()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._isSecure16329);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._isSecure16329);
}
internal static global::MonoJavaBridge.MethodId _getRoute16330;
global::org.apache.http.conn.routing.HttpRoute org.apache.http.conn.ManagedClientConnection.getRoute()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getRoute16330)) as org.apache.http.conn.routing.HttpRoute;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getRoute16330)) as org.apache.http.conn.routing.HttpRoute;
}
internal static global::MonoJavaBridge.MethodId _getSSLSession16331;
global::javax.net.ssl.SSLSession org.apache.http.conn.ManagedClientConnection.getSSLSession()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::javax.net.ssl.SSLSession>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getSSLSession16331)) as javax.net.ssl.SSLSession;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::javax.net.ssl.SSLSession>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getSSLSession16331)) as javax.net.ssl.SSLSession;
}
internal static global::MonoJavaBridge.MethodId _tunnelTarget16332;
void org.apache.http.conn.ManagedClientConnection.tunnelTarget(bool arg0, org.apache.http.@params.HttpParams arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._tunnelTarget16332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._tunnelTarget16332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _tunnelProxy16333;
void org.apache.http.conn.ManagedClientConnection.tunnelProxy(org.apache.http.HttpHost arg0, bool arg1, org.apache.http.@params.HttpParams arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._tunnelProxy16333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._tunnelProxy16333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _layerProtocol16334;
void org.apache.http.conn.ManagedClientConnection.layerProtocol(org.apache.http.protocol.HttpContext arg0, org.apache.http.@params.HttpParams arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._layerProtocol16334, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._layerProtocol16334, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _markReusable16335;
void org.apache.http.conn.ManagedClientConnection.markReusable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._markReusable16335);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._markReusable16335);
}
internal static global::MonoJavaBridge.MethodId _unmarkReusable16336;
void org.apache.http.conn.ManagedClientConnection.unmarkReusable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._unmarkReusable16336);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._unmarkReusable16336);
}
internal static global::MonoJavaBridge.MethodId _isMarkedReusable16337;
bool org.apache.http.conn.ManagedClientConnection.isMarkedReusable()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._isMarkedReusable16337);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._isMarkedReusable16337);
}
internal static global::MonoJavaBridge.MethodId _setIdleDuration16338;
void org.apache.http.conn.ManagedClientConnection.setIdleDuration(long arg0, java.util.concurrent.TimeUnit arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._setIdleDuration16338, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._setIdleDuration16338, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _flush16339;
void org.apache.http.HttpClientConnection.flush()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._flush16339);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._flush16339);
}
internal static global::MonoJavaBridge.MethodId _isResponseAvailable16340;
bool org.apache.http.HttpClientConnection.isResponseAvailable(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._isResponseAvailable16340, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._isResponseAvailable16340, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _sendRequestHeader16341;
void org.apache.http.HttpClientConnection.sendRequestHeader(org.apache.http.HttpRequest arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._sendRequestHeader16341, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._sendRequestHeader16341, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _sendRequestEntity16342;
void org.apache.http.HttpClientConnection.sendRequestEntity(org.apache.http.HttpEntityEnclosingRequest arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._sendRequestEntity16342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._sendRequestEntity16342, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _receiveResponseHeader16343;
global::org.apache.http.HttpResponse org.apache.http.HttpClientConnection.receiveResponseHeader()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HttpResponse>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._receiveResponseHeader16343)) as org.apache.http.HttpResponse;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HttpResponse>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._receiveResponseHeader16343)) as org.apache.http.HttpResponse;
}
internal static global::MonoJavaBridge.MethodId _receiveResponseEntity16344;
void org.apache.http.HttpClientConnection.receiveResponseEntity(org.apache.http.HttpResponse arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._receiveResponseEntity16344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._receiveResponseEntity16344, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _shutdown16345;
void org.apache.http.HttpConnection.shutdown()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._shutdown16345);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._shutdown16345);
}
internal static global::MonoJavaBridge.MethodId _close16346;
void org.apache.http.HttpConnection.close()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._close16346);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._close16346);
}
internal static global::MonoJavaBridge.MethodId _isOpen16347;
bool org.apache.http.HttpConnection.isOpen()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._isOpen16347);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._isOpen16347);
}
internal static global::MonoJavaBridge.MethodId _getMetrics16348;
global::org.apache.http.HttpConnectionMetrics org.apache.http.HttpConnection.getMetrics()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HttpConnectionMetrics>(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getMetrics16348)) as org.apache.http.HttpConnectionMetrics;
else
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::org.apache.http.HttpConnectionMetrics>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getMetrics16348)) as org.apache.http.HttpConnectionMetrics;
}
internal static global::MonoJavaBridge.MethodId _isStale16349;
bool org.apache.http.HttpConnection.isStale()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._isStale16349);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._isStale16349);
}
internal static global::MonoJavaBridge.MethodId _setSocketTimeout16350;
void org.apache.http.HttpConnection.setSocketTimeout(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._setSocketTimeout16350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._setSocketTimeout16350, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getSocketTimeout16351;
int org.apache.http.HttpConnection.getSocketTimeout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getSocketTimeout16351);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getSocketTimeout16351);
}
internal static global::MonoJavaBridge.MethodId _getLocalAddress16352;
global::java.net.InetAddress org.apache.http.HttpInetConnection.getLocalAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getLocalAddress16352)) as java.net.InetAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getLocalAddress16352)) as java.net.InetAddress;
}
internal static global::MonoJavaBridge.MethodId _getLocalPort16353;
int org.apache.http.HttpInetConnection.getLocalPort()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getLocalPort16353);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getLocalPort16353);
}
internal static global::MonoJavaBridge.MethodId _getRemoteAddress16354;
global::java.net.InetAddress org.apache.http.HttpInetConnection.getRemoteAddress()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getRemoteAddress16354)) as java.net.InetAddress;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getRemoteAddress16354)) as java.net.InetAddress;
}
internal static global::MonoJavaBridge.MethodId _getRemotePort16355;
int org.apache.http.HttpInetConnection.getRemotePort()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._getRemotePort16355);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._getRemotePort16355);
}
internal static global::MonoJavaBridge.MethodId _releaseConnection16356;
void org.apache.http.conn.ConnectionReleaseTrigger.releaseConnection()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._releaseConnection16356);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._releaseConnection16356);
}
internal static global::MonoJavaBridge.MethodId _abortConnection16357;
void org.apache.http.conn.ConnectionReleaseTrigger.abortConnection()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_._abortConnection16357);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::org.apache.http.conn.ManagedClientConnection_.staticClass, global::org.apache.http.conn.ManagedClientConnection_._abortConnection16357);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::org.apache.http.conn.ManagedClientConnection_.staticClass = @__env.NewGlobalRef(@__env.FindClass("org/apache/http/conn/ManagedClientConnection"));
global::org.apache.http.conn.ManagedClientConnection_._getState16326 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getState", "()Ljava/lang/Object;");
global::org.apache.http.conn.ManagedClientConnection_._setState16327 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "setState", "(Ljava/lang/Object;)V");
global::org.apache.http.conn.ManagedClientConnection_._open16328 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "open", "(Lorg/apache/http/conn/routing/HttpRoute;Lorg/apache/http/protocol/HttpContext;Lorg/apache/http/@params/HttpParams;)V");
global::org.apache.http.conn.ManagedClientConnection_._isSecure16329 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "isSecure", "()Z");
global::org.apache.http.conn.ManagedClientConnection_._getRoute16330 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getRoute", "()Lorg/apache/http/conn/routing/HttpRoute;");
global::org.apache.http.conn.ManagedClientConnection_._getSSLSession16331 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getSSLSession", "()Ljavax/net/ssl/SSLSession;");
global::org.apache.http.conn.ManagedClientConnection_._tunnelTarget16332 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "tunnelTarget", "(ZLorg/apache/http/@params/HttpParams;)V");
global::org.apache.http.conn.ManagedClientConnection_._tunnelProxy16333 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "tunnelProxy", "(Lorg/apache/http/HttpHost;ZLorg/apache/http/@params/HttpParams;)V");
global::org.apache.http.conn.ManagedClientConnection_._layerProtocol16334 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "layerProtocol", "(Lorg/apache/http/protocol/HttpContext;Lorg/apache/http/@params/HttpParams;)V");
global::org.apache.http.conn.ManagedClientConnection_._markReusable16335 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "markReusable", "()V");
global::org.apache.http.conn.ManagedClientConnection_._unmarkReusable16336 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "unmarkReusable", "()V");
global::org.apache.http.conn.ManagedClientConnection_._isMarkedReusable16337 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "isMarkedReusable", "()Z");
global::org.apache.http.conn.ManagedClientConnection_._setIdleDuration16338 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "setIdleDuration", "(JLjava/util/concurrent/TimeUnit;)V");
global::org.apache.http.conn.ManagedClientConnection_._flush16339 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "flush", "()V");
global::org.apache.http.conn.ManagedClientConnection_._isResponseAvailable16340 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "isResponseAvailable", "(I)Z");
global::org.apache.http.conn.ManagedClientConnection_._sendRequestHeader16341 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "sendRequestHeader", "(Lorg/apache/http/HttpRequest;)V");
global::org.apache.http.conn.ManagedClientConnection_._sendRequestEntity16342 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "sendRequestEntity", "(Lorg/apache/http/HttpEntityEnclosingRequest;)V");
global::org.apache.http.conn.ManagedClientConnection_._receiveResponseHeader16343 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "receiveResponseHeader", "()Lorg/apache/http/HttpResponse;");
global::org.apache.http.conn.ManagedClientConnection_._receiveResponseEntity16344 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "receiveResponseEntity", "(Lorg/apache/http/HttpResponse;)V");
global::org.apache.http.conn.ManagedClientConnection_._shutdown16345 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "shutdown", "()V");
global::org.apache.http.conn.ManagedClientConnection_._close16346 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "close", "()V");
global::org.apache.http.conn.ManagedClientConnection_._isOpen16347 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "isOpen", "()Z");
global::org.apache.http.conn.ManagedClientConnection_._getMetrics16348 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getMetrics", "()Lorg/apache/http/HttpConnectionMetrics;");
global::org.apache.http.conn.ManagedClientConnection_._isStale16349 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "isStale", "()Z");
global::org.apache.http.conn.ManagedClientConnection_._setSocketTimeout16350 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "setSocketTimeout", "(I)V");
global::org.apache.http.conn.ManagedClientConnection_._getSocketTimeout16351 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getSocketTimeout", "()I");
global::org.apache.http.conn.ManagedClientConnection_._getLocalAddress16352 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getLocalAddress", "()Ljava/net/InetAddress;");
global::org.apache.http.conn.ManagedClientConnection_._getLocalPort16353 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getLocalPort", "()I");
global::org.apache.http.conn.ManagedClientConnection_._getRemoteAddress16354 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getRemoteAddress", "()Ljava/net/InetAddress;");
global::org.apache.http.conn.ManagedClientConnection_._getRemotePort16355 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "getRemotePort", "()I");
global::org.apache.http.conn.ManagedClientConnection_._releaseConnection16356 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "releaseConnection", "()V");
global::org.apache.http.conn.ManagedClientConnection_._abortConnection16357 = @__env.GetMethodIDNoThrow(global::org.apache.http.conn.ManagedClientConnection_.staticClass, "abortConnection", "()V");
}
}
}
| |
/* Generated SBE (Simple Binary Encoding) message codec */
using System;
using System.Text;
using System.Collections.Generic;
using Adaptive.Agrona;
namespace Adaptive.Cluster.Codecs {
public class TimerEventEncoder
{
public const ushort BLOCK_LENGTH = 24;
public const ushort TEMPLATE_ID = 20;
public const ushort SCHEMA_ID = 111;
public const ushort SCHEMA_VERSION = 7;
private TimerEventEncoder _parentMessage;
private IMutableDirectBuffer _buffer;
protected int _offset;
protected int _limit;
public TimerEventEncoder()
{
_parentMessage = this;
}
public ushort SbeBlockLength()
{
return BLOCK_LENGTH;
}
public ushort SbeTemplateId()
{
return TEMPLATE_ID;
}
public ushort SbeSchemaId()
{
return SCHEMA_ID;
}
public ushort SbeSchemaVersion()
{
return SCHEMA_VERSION;
}
public string SbeSemanticType()
{
return "";
}
public IMutableDirectBuffer Buffer()
{
return _buffer;
}
public int Offset()
{
return _offset;
}
public TimerEventEncoder Wrap(IMutableDirectBuffer buffer, int offset)
{
this._buffer = buffer;
this._offset = offset;
Limit(offset + BLOCK_LENGTH);
return this;
}
public TimerEventEncoder WrapAndApplyHeader(
IMutableDirectBuffer buffer, int offset, MessageHeaderEncoder headerEncoder)
{
headerEncoder
.Wrap(buffer, offset)
.BlockLength(BLOCK_LENGTH)
.TemplateId(TEMPLATE_ID)
.SchemaId(SCHEMA_ID)
.Version(SCHEMA_VERSION);
return Wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH);
}
public int EncodedLength()
{
return _limit - _offset;
}
public int Limit()
{
return _limit;
}
public void Limit(int limit)
{
this._limit = limit;
}
public static int LeadershipTermIdEncodingOffset()
{
return 0;
}
public static int LeadershipTermIdEncodingLength()
{
return 8;
}
public static long LeadershipTermIdNullValue()
{
return -9223372036854775808L;
}
public static long LeadershipTermIdMinValue()
{
return -9223372036854775807L;
}
public static long LeadershipTermIdMaxValue()
{
return 9223372036854775807L;
}
public TimerEventEncoder LeadershipTermId(long value)
{
_buffer.PutLong(_offset + 0, value, ByteOrder.LittleEndian);
return this;
}
public static int CorrelationIdEncodingOffset()
{
return 8;
}
public static int CorrelationIdEncodingLength()
{
return 8;
}
public static long CorrelationIdNullValue()
{
return -9223372036854775808L;
}
public static long CorrelationIdMinValue()
{
return -9223372036854775807L;
}
public static long CorrelationIdMaxValue()
{
return 9223372036854775807L;
}
public TimerEventEncoder CorrelationId(long value)
{
_buffer.PutLong(_offset + 8, value, ByteOrder.LittleEndian);
return this;
}
public static int TimestampEncodingOffset()
{
return 16;
}
public static int TimestampEncodingLength()
{
return 8;
}
public static long TimestampNullValue()
{
return -9223372036854775808L;
}
public static long TimestampMinValue()
{
return -9223372036854775807L;
}
public static long TimestampMaxValue()
{
return 9223372036854775807L;
}
public TimerEventEncoder Timestamp(long value)
{
_buffer.PutLong(_offset + 16, value, ByteOrder.LittleEndian);
return this;
}
public override string ToString()
{
return AppendTo(new StringBuilder(100)).ToString();
}
public StringBuilder AppendTo(StringBuilder builder)
{
TimerEventDecoder writer = new TimerEventDecoder();
writer.Wrap(_buffer, _offset, BLOCK_LENGTH, SCHEMA_VERSION);
return writer.AppendTo(builder);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.